user1406196
user1406196

Reputation: 147

Java Regexp Matcher

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

Answers (3)

Mattias Isegran Bergander
Mattias Isegran Bergander

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

SuperJulietta
SuperJulietta

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

beerbajay
beerbajay

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

Related Questions