1

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.

1
  • 1
    What programming language are you using? Commented Sep 25, 2022 at 3:18

2 Answers 2

3

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 {.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.