简体   繁体   中英

java regex quantifiers

I have a string like

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

I have tried

Pattern pattern = Pattern.compile("number\\d+(.*)(number\\d+)?");
Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
    System.out.println(matcher.group());
}

but this gives

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).)*");

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.

Explanation of my solution:

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.
Pattern pattern = Pattern.compile("\\w+\\d(\\s\\w+)\1*");
Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    System.out.println(matcher.group());
}

because .* is a greedy pattern. use .*? instead of .*

Pattern pattern = Pattern.compile("number\\d+(.*?)(number\\d+)");
Matcher matcher = pattern.matcher(string);
while(matcher.find();){
    out(matcher.group());
}

如果“foobar”只是一个例子而且你的意思是“任何单词”使用以下模式:( (number\\\\d+)\\s+(\\\\w+)

为什么不匹配number\\\\d+ ,查询匹配位置,自己进行字符串拆分?

(.*) part of your regex is greedy, therefore it eats everything from that point to the end of the string. Change to non-greedy variant: (.*)?

http://docs.oracle.com/javase/tutorial/essential/regex/quant.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM