tricpod
tricpod

Reputation: 23

Java Regexp Groups

I need a expression to extract some alternatives. The input is:

asd11sdf33sdf55sdfg77sdf

I need the 11 33 and 55 but not 77.

I tried first:

.*(((11)|(33)|(55)).*)+.*

So I got only 55. But with lazy (non greedy)

.*?(((11)|(33)|(55)).*)+.*

I got only 11. How to get all?

regards Thomas

Upvotes: 2

Views: 355

Answers (3)

Dante WWWW
Dante WWWW

Reputation: 2739

try to use

.*?(11|33|55)

as your regexp to compile the pattern, and use the loop in fge's answer. (and I think his answer is more universal and meaningful...

This is because the .* or something after (11|33|55) in your regexp matches the whole string after 11. (and if you use greedy match the .* before (11|33|55) will match the whole string before 55... just because it is greedy)

This way you will get a match whose match(1) is 11, find() is the match of string after 11.

tested with http://www.regexplanet.com/simple/index.html

Upvotes: 0

Ingo Kegel
Ingo Kegel

Reputation: 47975

Groups are fixed, you cannot use "+" on a group to get a list of matches. You have to do this with a loop:

    Pattern p = Pattern.compile("((11)|(33)|(55))");
    Matcher m = p.matcher("asd11sdf33sdf55sdfg77sdf");
    int start = 0;
    List<String> matches = new ArrayList<String>();
    while (m.find()) {
        matches.add(m.group());
    }
    System.err.println("matches = " + matches);

Upvotes: 1

fge
fge

Reputation: 121710

Use (?!77)(\d\d) as a Pattern and while (m.find()) { m.group(1) } where m is a Matcher.

Upvotes: 2

Related Questions