java正则表达式量词 [英] java regex quantifiers
本文介绍了java正则表达式量词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串
String string = "number0 foobar number1 foofoo number2 bar bar bar bar number3 foobar";
我需要正则表达式给我以下输出:
I need a regex to give me the following output:
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
推荐答案
所以你想要数字
(+一个整数)后跟任何东西,直到下一个数字
(或字符串结束),对吧?
So you want number
(+ an integer) followed by anything until the next number
(or end of string), right?
然后你需要告诉正则表达式引擎:
Then you need to tell that to the regex engine:
Pattern pattern = Pattern.compile("number\\d+(?:(?!number).)*");
在正则表达式中,。*
匹配尽可能多 - 直到字符串结尾的所有内容。另外,你创建了第二部分(number \\d +)?
比赛本身的一部分。
In your regex, the .*
matched as much as it could - everything until the end of the string. Also, you made the second part (number\\d+)?
part of the match itself.
我的解决方案说明:
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.
这篇关于java正则表达式量词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文