1

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;

  • No space at the beginning but allow spaces inbetween words.
  • There must be a space before a - if it isn't the first -.
  • There should be no limit to how many you can enter as long as they fit the pattern. For example these would all be fine; -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!

2
  • 1
    To match such a line you could use ^-[^\s-][^-]*(?:\s-[^\s-][^-]*)*$ and to extract, you may use (?<!\S)-[^\s-][^-]* Commented Jul 29, 2020 at 13:57
  • @WiktorStribiżew Sorry I only got around to testing it now. Yes it does! Many Thanks! Commented Jul 30, 2020 at 5:50

1 Answer 1

1

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.
Sign up to request clarification or add additional context in comments.

2 Comments

Hey I found a bit of a flaw in this. With the example -m -fd teststring it matches when teststring should require a dash before it. Any ideas? :)
@Borassign Maybe you want ^-[^\s-]+(?:\s-[^\s-]+)*$ and (?<!\S)-[^\s-]+?

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.