Reputation: 781
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;
-
if it isn't the first -
.-m -fd -optional
but something like this wouldnt be; -m-fd teststring
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
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