我的代码如下:
@Test
public void testMatcher2(){
String pa2 = "^\\s*(\\w+)\\.(\\w+)\\s*(EQUALS|NOT_EQUALS)\\s*(.*$)";
Pattern p = Pattern.compile(pa2, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher("Class.fieldNOT_EQUALS'someval'");
boolean bb = m.find();
System.out.println(bb); //#1
System.out.printf("A=%s. B=%s. C=%s\n", m.group(1),m.group(2),m.group(3));
while (m.find()){ //#2
System.out.println("a");
String a = m.group(1);
String b = m.group(2);
String c = m.group(3);
System.out.printf("a=%s. b=%s. c=%s\n", a,b,c);
}
}
结果如下:
true
A=Class. B=fieldNOT_. C=EQUALS
我的问题是:
m.find() 独立调用时返回 true(#1),为什么在 while()(#2) 中调用时返回 false?
在此正则表达式中,
Class.fieldNOT_EQUALS'someval'
可以分为 2 个结果(我认为):Class/field/NOT_EQUALS/'someval'
(R1,这就是我想要的)和Class/fieldNOT_/EQUALS/'someval'
(R2,程序的结果),为什么Matcher
将exp分成R2?如果我想在不改变exp的情况下获得R1,如何获得?
任何答案都值得赞赏。
最佳答案
m.find() return true when called it independently(#1), why it return false called in while()(#2).
请参阅 Matcher
的 Javadoc:http://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html
This method [find] starts at the beginning of this matcher's region, or, if a previous invocation of the method was successful and the matcher has not since been reset, at the first character not matched by the previous match.
至于第二个问题,你的 Matcher
之所以如此划分它是贪婪匹配:Matcher
在匹配每个部分时尝试获取尽可能多的字符正则表达式的。 NOT_
不是由表达式的 (EQUALS|NOT_EQUALS)
部分使用,而是由早期的通配符使用。使用不情愿的量词(请参阅 Pattern 上的 Javadoc)而不是贪婪的量词来解决此问题。
关于java - Java 中的 Matcher.find() 对正则表达式进行分组时出现错误结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20190880/