Java regex quantifiers

I have a line 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 tried

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

but it gives

 number0 foobar number1 foofoo number2 bar bar bar bar number3 foobar 
+7
source share
6 answers

So you want number (+ an integer) followed by something until the next number (or end of line), right?

Then you need to report this to the regex engine:

 Pattern pattern = Pattern.compile("number\\d+(?:(?!number).)*"); 

In your regular expression .* Matched as much as you could - everything to the end of the line. Also, did you do the second part (number\\d+)? part 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. 
+10
source

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

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

If "foobar" is just an example, and you really mean "any word", use the following pattern: (number\\d+)\s+(\\w+)

0
source

Why aren't you just in charge of number\\d+ , asking for the location of the match, and splitting the String yourself?

0
source
 Pattern pattern = Pattern.compile("\\w+\\d(\\s\\w+)\1*"); Matcher matcher = pattern.matcher(string); while (matcher.find()) { System.out.println(matcher.group()); } 
0
source

(.*) part of your regular expression is greedy, so it eats everything from that point to the end of the line. Go to the unwanted option: (.*)?

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

-one
source

All Articles