简体   繁体   中英

Optional regex character group

I am trying to write a regex to validate some command line parameters, I have got it working but it doesn't seem very efficient, and with more to come I'd like to see if there's a way of grouping the parameter's together.

The command line has 3 optional parameters, -h -s -r , they might all be used, they might not be used at all.

The regex I have at the moment is

myapp.exe\s?(-h\s*)?\s?(-s\s*)\s?(-r\s*)?

Do I have to keep repeating \\s?(-x\\s*) for every parameter, or can I group them together? Something like \\s?(-h,-r,-s\\s*) would be very helpful!

Thanks

You can use something like that:

myapp\.exe\s?(-[hsr]\s*)*

Don't forget to escape dots if you want the regex to match a literal dot.

[ ... ] is a character class and will match any one (or range if you define any) character inside.

regex101 demo


EDIT: To ensure that a flag is not duplicated, you can use a backreference and a negative lookahead, along with an end of line anchor:

myapp\.exe\s?(?:-([hsr])(?!.*\1)\s*)*$

\\1 will refer to whatever is captured in ([hsr])

(?! ... ) will negate the match if whatever inside is matched

$ will ensure that the whole string is checked. You might want to remove that part if there is anything else coming after the string you provided in your question to make it properly match.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM