Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java regex quantifiers

Tags:

java

regex

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
like image 241
b3bop Avatar asked Feb 09 '12 07:02

b3bop


1 Answers

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.
like image 95
Tim Pietzcker Avatar answered Oct 13 '22 15:10

Tim Pietzcker