1

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".

3 Answers 3

7

The + quantifier is greedy so it matches as much as possible. You should the reluctant version of this quantifier +?; your pattern then becomes:

(.+?)1
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

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].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.