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

Validating a url path with regex and excluding special characters

I’m trying to write up an expression that starts with a ‘#" and takes in the following types of paths and only takes in a character A-z/a-z and doesn’t accept digits or special characters:
Example valid paths:

#/
#/word/word
#/word
#/word/word/word

This is what I have currently:

#\/\D+|\/\D+

I have also tried:

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

#\/\D+|\s\/^[A-Za-z\s]*$

It filters 85% of the paths correctly but it still accepts paths with special characters as valid such as "#/word/word?test=word" "#/word/word=%"

I’m not quite sure what I am missing.

>Solution :

I would phrase the regex as:

^(?:#/|#/[A-Za-z]+(?:/[A-Za-z]+)*)$

This regex says to match:

  • ^ from the start of the string
  • (?:
    • #/ match #/ by itself
    • | OR
    • #/ match #/
    • [A-Za-z]+ followed by a path name
    • (?:/[A-Za-z]+)* followed by zero or more other paths
  • )
  • $ end of the string

Demo

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