-2

I want to validate a string with alpha numeric values, but if the string contains -- (double dash) anywhere in the string, it should be invalid.

valid:

  • apple123
  • -apple-123
  • app-le123
  • a-p-p-l-e-1-2-3

invalid:

  • --apple123
  • app--le123

https://stackoverflow.com/a/1240365/1920590

The above old post have the answer ^(?!.*bar).*$ which does the negation, but it does not work for same character repetition like --.

Can anyone help me to figure out to modify the ^(?!.*bar).*$ to identify -- as a string.

anubhava
  • 761,203
  • 64
  • 569
  • 643
Sandun Perera
  • 541
  • 6
  • 21

1 Answers1

1

You may use a negative lookahead:

^(?!.*--)[\w-]+$
  • (?!.*--) is a negative lookahead assertion that will fail the match if -- appears anywhere in input.
  • [\w-] matches a word character [a-zA-Z0-9_] or a hyphen

RegEx Demo

anubhava
  • 761,203
  • 64
  • 569
  • 643