Home > OS >  Unmatch when Slash( / ) is followed by Underscore( _ ) or hyphen( - )
Unmatch when Slash( / ) is followed by Underscore( _ ) or hyphen( - )

Time:05-17

I am constructing an ID, in Javascript, which doesn't allow special character and uppercase letter. We could have / _ - in the ID, but the it should not begin with these.

  • hello correct
  • helloWorld incorrect
  • 123hello correct
  • hello/world correct
  • -hello incorrect
  • _hello incorrect
  • $hello incorrect
  • /hello incorrect
  • hello$ incorrect
  • hello_world correct
  • hello-world correct
  • hello-world/apple correct
  • hello_world/apple correct
  • hello_world/apple123 correct

I have the following regEx which almost handles all the cases, however there is one case where if slash(/) is present it should not be followed by hyphen(-) or underscore(_), which i am unable to solve

^(?=.{1,50}$)(([a-z0-9]) ([-_/a-z0-9])*)$

  • hello_world/-apple incorrect
  • hello_world/_apple incorrect
  • hello_world//apple incorrect

Any help on this would be much appreciated.

CodePudding user response:

You can use

^(?=.{1,50}$)[a-z0-9] (?:[-_\/][a-z0-9] )*[-_\/]?$

See the regex demo.

Details:

  • ^ - string start
  • (?=.{1,50}$) - there can only be 1 to 50 chars in the string
  • [a-z0-9] - one or more lowercase ASCII letters or digits
  • (?:[-_\/][a-z0-9] )* - zero or more sequences of
    • [-_\/] - a -, _ or / char
    • [a-z0-9] - one or more lowercase ASCII letters or digits
  • [-_\/]? - an optional -, _ or / char
  • $ - end of string.
  • Related