Rohit Verma Rohit Verma - 6 months ago 20
Javascript Question

Javascript Regular expression : ^[^/\s/]+[a-z]{1,}[0-9]*[\-\_]*[^\/][^/\s/]$

I want to create a regular expression which will:


  • not contain any space and special characters except "-" and "_"

  • it should contain at least one alphabet character



The regular expression I created is:

^[^/\s/]+[a-z]{1,}[0-9]*[\-\_]*[^\/][^/\s/]$


It only only matches if my string contains at least 4 characters, including 1 alphabet. I tried it on https://regex101.com/#javascript Can someone help me what I am doing wrong here.

Answer

You need to learn about lookaround. One solution to your problem is:

/(?=^[\w-]{4,}$)(.*[a-z].*)/gmi
  • (?=^[\w-]{4,}$) will assert that you input will contains only chars in the range a-z, digit, _ and , - with a length of at least 4.
  • (.*[a-z].*) ensure that there will be at least one char in the range a-z.

See Demo