java-record
java正则
今天写正则,遇到个问题:
String reg = "1+", str = "a1111a";
Pattern p = Pattern.compile(reg);
Matcher m = p.matcher(str);
boolean b = m.find();
boolean b1 = m.matches();
boolean b3 = Pattern.matches(reg, str);
System.out.println("b is " + b); // b is true
System.out.println("b1 is " + b1); // b1 is false
System.out.println("b3 is " + b3); // b3 is false
由于写js正则的习惯,我以为 b3 应该是输出 true 才对,但是情况却不是这样。
探究原因,应该是 matches()
方法的问题。
根据百度,matches() 应该是全词匹配,我个人任务,等同于 js /^1+$/
这种模式。
但是,find()
是查找的意思,所以不用全词匹配。因此
String reg = "^1+", str = "a1111a";
Pattern p = Pattern.compile(reg);
Matcher m = p.matcher(str);
boolean b = m.find();
boolean b1 = m.matches();
boolean b3 = Pattern.matches(reg, str);
System.out.println("b is " + b); // b is false
System.out.println("b1 is " + b1); // b1 is false
System.out.println("b3 is " + b3); // b3 is false
输出全是 false
了,因为,find()
要找数字1开头的字符串,找不打了,所以也false
我做了实验:
String reg = "[0-9]+[a-zA-Z]+[0-9]+", str = "123abcd0987";
Pattern p = Pattern.compile(reg);
Matcher m = p.matcher(str);
boolean b = m.find();
boolean b1 = m.matches();
boolean b3 = Pattern.matches(reg, str);
System.out.println("b is " + b); // b is true
System.out.println("b1 is " + b1); // b1 is true
System.out.println("b3 is " + b3); // b1 is true
因为全词匹配的,所以 matches()
返回 true
了。
但是,我在字符串后面加个字母
String reg = "[0-9]+[a-zA-Z]+[0-9]+", str = "123abcd0987a";
Pattern p = Pattern.compile(reg);
Matcher m = p.matcher(str);
boolean b = m.find();
boolean b1 = m.matches();
boolean b3 = Pattern.matches(reg, str);
System.out.println("b is " + b); // b is true
System.out.println("b1 is " + b1); // b1 is false
System.out.println("b3 is " + b3); // b1 is false
他又 false
了。
看来想让 java 像 js 那样用,还是 用 find()
好一些。
最后: Pattern.matches()
内部就是调用的 Matcher
的 matches()
方法;
贴一下源代码:
public static boolean matches(String regex, CharSequence input) {
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
return m.matches();
}
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!