Negative lookahead doesn't behave as expected

Viewed 71

Trying to use regex to parse arguments from a string: "-a 1 -b -5.1".

Output should have 2 flags with values: flag a with value 1, b with -5.1.

When I try (-(?<flag>[a-zA-Z])(?<value> .+)?(?!-[a-zA-Z]))* regular expression, it returns only flag a with value 1 -b -5.1.

Why doesn't it stop at -b?

1 Answers

You need to make (?<value> .+) lazy and turn the negative lookahead into a positive lookahead.

Here is my try:

-(?<flag>[a-zA-Z]) (?<value>.+?)(?=$| -[a-zA-Z])

Demo

Explanation:

You are probably wondering why a positive lookahead is used instead of a negative one. This is because +? will stop matching whenever the thing after it matches. This is why we look ahead to find $| -[a-zA-Z] and if we do find one, +? stops matching!

I have also moved a space character outside of the value group. I assume you don't want the value to contain spaces?

Related