Reputation: 1421
(-[a-zA-Z]+=?)+(([^\s]+)|(\s+((["'])(?:(?=(\\?))\2.)*?\6)))
I have a bunch of command line arguments.
-arg1 -arg2 -arg3=500 -arg4=-250,200,50.0 -arg5 "Hello World" -arg6 "[I don't know whats going on /here/]"
I'm not particularly good at regex, and was using regexr.com to verify my results. Regex.Matches with the expression from this site usually works copy and pasted out no problem. This time its not.
The results of using that command line string is as follows:
Count = 6
[0]: "-arg1"
[1]: "-arg2"
[2]: "-arg3=500"
[3]: "-arg4=-250,200,50.0"
[4]: "-arg5"
[5]: "-arg6"
And this is looping through Regex.Matches and each Captures
I can't figure out why the quotes won't become part of the match. Is it maybe a whitespace issue with the |(\s+((["']
part?
Upvotes: 2
Views: 67
Reputation: 20486
Update:
I tweaked this per your comment. I pulled the optional space (\s*
) into a non capturing group with a space OR an equal sign. You'll also see I moved the quotation capture first in the alternation since \S+
would start matching "foo
and we don't want that.
(-\w+)(?:=|\s)?("[^"]*"|\S+)?
I cleaned this up a bit in general, let me know if there's any missing functionality from the original expression you wrote:
(-\w+)\s*((?:=\S+)|"[^"]*")?
There's a couple things breaking your original expression, including:
\2
or \6
references\d
capture for the argument key (-[a-zA-Z]+=?
)Upvotes: 3