user104309
user104309

Reputation: 690

Java - all substring for a given regex

I have a pattern like the following

API:ADD|TYPE:ABC...MATCH:TRUE

[LOTS OF OTHER LOG LINES]

API:ADD|TYPE:ABC...MATCH:TRUE

[LOTS OF OTHER LOG LINES]

API:ADD|TYPE:DEF...MATCH:TRUE

I tried the following regex:

(API:.*MATCH:(TRUE|FALSE))

while (matcher.find()) {
    System.out.println(i + " occurence");
    i++;
    matches.add(matcher.group());
}

It matches from first "API" to last "TRUE" and hence only one substring is returned! I want three substrings (in this scenario) starting from "API" till either "TRUE" or "FALSE".

Appreciate your help in this regard.Thanks.

Edit:

-------------------------------------------------------
20:31:57    CALL    add     35  
-------------------------------------------------------
20:31:57    REASON  API:ADD|TYPE:ABC|ErrorType:VALIDATION|Error Message:User already has|MATCH:FALSE 

Upvotes: 1

Views: 87

Answers (2)

Stefan Winkler
Stefan Winkler

Reputation: 3966

This is because you use .* which is a greedy quantifier.

You should try to use .*? which is reluctant -- that means that it matches the smallest possible substring.

For more info about greedy vs. reluctant see the excellent answers here: Greedy vs. Reluctant vs. Possessive Quantifiers

Upvotes: 1

Ravi K Thapliyal
Ravi K Thapliyal

Reputation: 51721

Use a non-greedy quantifier .*? and the regex will start matching as little as possible.

(API:.*?MATCH:(TRUE|FALSE))

Upvotes: 1

Related Questions