Borassign
Borassign

Reputation: 781

How to match "command line argument" style strings with regex?

I'm trying to validate a string I use in one of my applications, and the structure of it is basically the same as linux command line arguments.

E.G -m -b -s etc...

I'm basically trying to make the pattern;

I managed to get as far as ^-[a-zA-Z]\s but I'm not sure how to make this repeat! This also doesn't work on flags longer than 1 character and also has some issues with spaces!

Upvotes: 1

Views: 1442

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626699

To match and validate such a line you could use

^-[^\s-][^-]*(?:\s-[^\s-][^-]*)*$

See the regex demo.

To extract each option, you may use

(?<!\S)-[^\s-][^-]*

See this regex demo.

Details

  • ^ - start of a string
  • - - a hyphen
  • [^\s-][^-]* - any char other than whitespace and - and then 0 or more chars othee than -
  • (?:\s-[^\s-][^-]*)* - 0 or more repetitions of
    • \s - a whitespace
    • - - a hyphen
    • [^\s-][^-]* - any char other than whitespace and - and then 0 or more chars othee than -
  • $ - end of string.

Upvotes: 1

Related Questions