Regex that checks for the validity of options, disallowing duplicates

Viewed 54

I'm trying to find a regex to check for the validity of options that are supplied with a command.

Say that -a, -b and -c are valid options. They may be combined, for example as -ac or -abc. Order doesn't matter, so -ba is also valid. I thought this regex would do the trick:

^-[abc]{1,3}$

But it has a downside. This regex also accepts duplicates, i.e. -abb.

How do I modify this regex to disallow duplicates?

2 Answers

You may use this regex with a capture group and a negative lookahead:

^-((?!.*\1)[abc]){1,3}$

RegEx Demo

RegEx Details:

  • ^: Start
  • -: Match a -
  • (: Start capture group #1
    • (?!.*\1): Negative lookahead to make sure we don't have repeat of what we have in capture group #1 anywhere in the input
    • [abc]: Match a or b or c
  • ){1,3}: End capture group #1. Repeat this group 1 to 3 times
  • $: End

You could list all the alternatives, but if it is a long character class, you can check that on the right side there is no char that is already captured using a capture group and a backreference.

^-(?![abc]*?([abc])[abc]*?\1)[abc]{1,3}$
  • ^ Start of string
  • - Match a hyphen
  • (?! Negative lookahead, assert that at the right is not
    • [abc]*([abc])[abc]*\1 Match optional chars a, b or c and then capture 1 char. Then check that the captured char does not occur at the right side
  • ) Close lookahead
  • [abc]{1,3} Match 1-3 times a b or c
  • $ End of string

Regex demo

Or a short version using only non whitespace chars, as the character class can only match 3 chars.

^-(?!\S*(\S)\S*\1)[abc]{1,3}$

Regex demo

Related