java正则表达式量词
我有一个字符串
String string = "number0 foobar number1 foofoo number2 bar bar bar bar number3 foobar";
我需要一个正则表达式给我以下输出:
number0 foobar number1 foofoo number2 bar bar bar bar number3 foobar
我努力了
Pattern pattern = Pattern.compile("number\\d+(.*)(number\\d+)?"); Matcher matcher = pattern.matcher(string); while (matcher.find()) { System.out.println(matcher.group()); }
但这给了
number0 foobar number1 foofoo number2 bar bar bar bar number3 foobar
所以你想要number
(+一个整数)后跟任何东西,直到下一个number
(或字符串的结尾),对吗?
然后你需要告诉正则表达式引擎:
Pattern pattern = Pattern.compile("number\\d+(?:(?!number).)*");
在你的正则表达式中, .*
尽可能多地匹配 – 直到字符串结尾的所有内容。 另外,你做了第二部分(number\\d+)?
比赛本身的一部分。
解释我的解决方案:
number # Match "number" \d+ # Match one of more digits (?: # Match... (?! # (as long as we're not right at the start of the text number # "number" ) # ) . # any character )* # Repeat as needed.
如果“foobar”只是一个例子而且你的意思是“任何单词”使用以下模式:( (number\\d+)\s+(\\w+)
为什么不匹配number\\d+
,查询匹配位置,自己进行字符串拆分?
因为.*
是一种贪婪的模式。 使用.*?
而不是.*
Pattern pattern = Pattern.compile("number\\d+(.*?)(number\\d+)"); Matcher matcher = pattern.matcher(string); while(matcher.find();){ out(matcher.group()); }
Pattern pattern = Pattern.compile("\\w+\\d(\\s\\w+)\1*"); Matcher matcher = pattern.matcher(string); while (matcher.find()) { System.out.println(matcher.group()); }
(.*)
正则表达式的一部分是贪婪的,因此它会吃掉从该点到字符串末尾的所有内容。 改为非贪婪的变种: (.*)?
http://docs.oracle.com/javase/tutorial/essential/regex/quant.html