Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unmatch when Slash( / ) is followed by Underscore( _ ) or hyphen( – )

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])*)$

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Any help on this would be much appreciated.

>Solution :

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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading