Home > OS >  Regex for seperating command and parameters
Regex for seperating command and parameters

Time:09-26

I am trying to find a regex that can match my desired format of a command. I am not very familiar with Regex, but after playing around with it, I have got some progress even though it still does not satisfy my need.

My desired command format would be: parameter flagged by - and value(s) of each parameter would be either single value or multi-value enclosed by {}. Example:

-name Test -types {One,Two,Three}

What I have now is this regex: [\-][a-zA-Z0-9]*\s[a-zA-Z0-9]* which would only satisfy, in my case, a command with single value for each parameter. For example

-name Test -type One

I have tried the regex [\-][a-zA-Z0-9]*\s([a-zA-Z0-9]*|{[a-zA-Z0-9,]*}) which kind of makes sense for me. However, in reality it doesn't work. It still only matches single-value format or only the parameter part that has a multivalue.

Not sure if someone can help me to provide me an appropriate regex for my command? I am not sure why the one I have is not working.

CodePudding user response:

Match the different param formats using an alternation, matching the list type first:

-([a-zA-Z0-9] )\s*(\{[a-zA-Z0-9] (?:,[a-zA-Z0-9] )*\}|[a-zA-Z0-9]*)

See live demo.

Group 1 of each match is the option and group 2 is the parameter (if any - this regex allows for parameterless options).


If your language/tool supports \w (ie "word characters"), you can significantly improve readability by replacing every occurrence of [a-zA-Z0-9] with \w. Note that \w also matches the underscore character, but I think your pattern should too.

CodePudding user response:

Reverse the order of contents in the brackets, which is: ({[a-zA-Z0-9,]*}|[a-zA-Z0-9]*).

Because [a-zA-Z0-9]* can match an empty string, the regular expression will match it with a higher priority instead of trying to search for a curly bracket {.

  • Related