java如何运行正则?
String自带的matches()方法验证。但这种验证是调用了Pattern的matches方法。
public boolean matches(String regex) {return Pattern.matches(regex, this);//底层源码}
编译正则表达式
public static void main(String[] args) {String str="efsefsef2@2@2222";//?<! 匹配\\w+前面跟的不是\\d的内容String reg="(?<!\\d)\\w+";Pattern pattern=pile(reg);//先编译正则//再把字符串加入到matcher对象Matcher matcher=pattern.matcher(str);//开始局部匹配遇到第一个符合条件的就停止匹配matcher.find();System.out.println(matcher.group());}
运行结果:
贪婪与懒惰
当我们不对*,+,?做处理时他就是贪婪的每次匹配都偏向于多的一方。
public static void main(String[] args) {String str="efsefsef2@2@2222";String reg="\\w+"; //\w 字母数字下划线 ?<= ?! ?:Pattern pattern=pile(reg);Matcher matcher=pattern.matcher(str);matcher.find();System.out.println(matcher.group());}
结果:
当我们想让他懒惰时,让他偏向少的一方可以在后面加上?来让我们试下。
public static void main(String[] args) {String str="efsefsef2@2@2222";String reg="\\w+?"; //\w 字母数字下划线 ?<= ?! ?:Pattern pattern=pile(reg);Matcher matcher=pattern.matcher(str);matcher.find();System.out.println(matcher.group());}
结果:
public static void main(String[] args) {String str="efsefsef2@2@2222";String reg="\\w*?"; //\w 字母数字下划线 ?<= ?! ?:Pattern pattern=pile(reg);Matcher matcher=pattern.matcher(str);matcher.find();System.out.println(matcher.group());}
结果:
同理其他只要加上?就会变得懒惰。