-2

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.

Michael Gaskill
  • 7,913
  • 10
  • 38
  • 43
Rohit Verma
  • 299
  • 1
  • 8
  • Will appreciate if someone can help me for regular expression resources where I can learn and master it. – Rohit Verma May 19 '16 at 05:42
  • Basically you want something like this: http://stackoverflow.com/questions/5068843/password-validation-regex. Or this: http://stackoverflow.com/questions/2370015/regular-expression-for-password-validation. Or this: http://stackoverflow.com/questions/21760692/regular-expression-for-password-validation-c-sharp... – Aran-Fey May 19 '16 at 05:46
  • @Rawing Thanks, I will try something with this. Just FYI, this will be basically a string which I want to append with URL. so I want to allow only "-" & "_" not even "/" – Rohit Verma May 19 '16 at 06:10
  • Can someone let me know, why it is downvoted? – Rohit Verma May 19 '16 at 07:26
  • @RohitVerma Can you answer the question in these comments? Which is the correct criteria for your question? – Michael Gaskill May 19 '16 at 10:43

2 Answers2

2

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

Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
1

Using fundamental regex primitives, you can use this:

/^[0-9_-]*[a-z]+[0-9a-z_-]*$/i

It works correctly with these sample input strings:

  • 999c123-
  • a123-88asd
  • 9923--_b
  • B
  • 99-luftballoons
  • Z8f

And does not match these strings:

  • 999
  • -51-
  • ---_-

It's fast and will work in pretty much every regex engine, even non-standard (non-extended) grep.

Michael Gaskill
  • 7,913
  • 10
  • 38
  • 43