pchris
pchris

Reputation: 35

Optional lookahead in regular expression

I have a string like this:

REFORMAT FIELDS=(F1:%[VER#,SAH#]%,%SAH#%,F2:%KMSTAND%) 

And I am trying to use the following regular expression to get all the characters after "F1:" until "F2":

(F1|F2):(.*?)(?:(?=,F))

It matches the first portion but it should also get the second. So that the lookahead function works only optional. What's wrong?

Edit: My code:

Matcher fields = Pattern.compile("(F1|F2):(.*?)(?:(?=,F))").matcher(line);
while (fields.find()) {
    //do something with fields.group(2)
}

Upvotes: 1

Views: 1302

Answers (1)

Bergi
Bergi

Reputation: 664538

So that the lookahead function works only optional. What's wrong?

An optional lookahead would be quite useless. And in your case, you want to lookahead after matching F2 - only you won't look out for ,F, but for the string end.

Change your pattern to

(F1|F2):(.*?)(?=,F|\)) // "(F1|F2):(.*?)(?=,F|\\))" with double-escaped brace
// maybe:
(F\d):(.*?)(?=,F\d|\)) 

or

(F1|F2):(.*?)(?:$|(?=,F))

if you want to include the closing parenthesis

Upvotes: 2

Related Questions