【发布时间】:2014-03-31 11:05:29
【问题描述】:
我有一个这样的字符串:
"value of <abc/def> ends with <def> and value of <abc/def> does not end with <abc> and value of <abc> is <abc>"
我想提取字符串value of <abc/def> does not end with <abc>。
我使用了以下模式
String text = "value of <abc/def> ends with <def> and value of <abc/def> does not end with <abc> and value of <abc> is <abc>";
String patternString1 = "(value\\s+of\\s+(<.*>)\\s+ends\\s+with\\s+(<.*>))";
Pattern pattern = Pattern.compile(patternString1);
Matcher matcher = pattern.matcher(text);
while(matcher.find()) {
System.out.println("found: " + matcher.group(1));
}
结果:-
found: value of <abc/def> ends with <def> and value of <abc/def> does not end with <abc> and value of <abc> is <abc>
【问题讨论】:
-
.*默认为greedy。您需要通过添加?使其变得懒惰。至少我认为这是问题所在——我不太明白这个问题。 -
我真的不知道你的真正意思是什么,但也许修改
*的贪婪会成功,改为*?。这将尽可能少地抓取字符。 -
为什么你的正则表达式试图匹配
ends with-part,而你说,你想匹配does not end with-part?这有点令人困惑。