Reputation: 147
Simple question about regexps. I've got
String text = "foobar1foobar1";
And I need to get part before first 1 (foobar) When I do something like that:
Pattern date_pattern = Pattern.compile("(.+)1");
Matcher matcher = date_pattern.matcher(text);
matcher.group(1);
But I recieve "foobar1foobar".
Upvotes: 1
Views: 204
Reputation: 11909
Greedy and non greedy regexps. .+
is greedy and will make the longest possible match. Adding a ?
will make it non-greedy: .+?
For your example you don't really need a regexp though, but I guess it was just an example. Instead you could do this with your example:
String firstPart = text.substring(0, text.indexOf('1'))
or even a (very simple) regexp in split:
String firstPart = text.split("1")[0]
Both would be easier to read than regexp for most people. Be careful if you don't have an "1" in there though.
Upvotes: 2
Reputation: 6821
An alternative may be using split function:
String s="foobar1foobar2";
String[] splitted = s.split("1");
The string you are searching for is in splitted[0].
Upvotes: 1
Reputation: 20270
The +
quantifier is greedy so it matches as much as possible. You should the reluctant version of this quantifier +?
; your pattern then becomes:
(.+?)1
Upvotes: 7