Home > Net >  RegEx- first character should not contain special characters and subsequent characters should not co
RegEx- first character should not contain special characters and subsequent characters should not co

Time:05-27

I have a specific validation scenario. The first character of the string should not contain special characters which I can achieve using /^[!@#$%^&*()_ \-=\[\]{};':"\\|,.<>\/?] $/, but subsequent characters should not contain specific special characters, which are !@$%^* =\[\]{};:\\|<>? I tried that using regex /^[!@#$%^&*()_ \-=\[\]{};':"\\|,.<>\/?][!@$%^* =\[\]{};:\\|<>?] $/ and negating the result but its not working. I want to allow all other characters other than these special characters so I am trying to negate the result of above regex. What I mean is, first character should accept everything except special character and subsequent chars should accept everything except specified special characters.

CodePudding user response:

You were close. Just missing using ^ inside a character class to negate it, and maybe instead of * to allow an empty string.

Match start of string: ^
Match a single character that's not one of !@#$%^&*()_ -=[]{};':"|,.<>/?: [^!@#$%^&*()_ \-=\[\]{};':"\\|,.<>\/\?]
Match a string of any length that doesn't contain one of !@$%^* =[]{};:|<>?: [^!@$%^* =\[\]{};:\\|<>\?]*
Match end of string: $

Complete regex: ^[^!@#$%^&*()_ \-=\[\]{};':"\\|,.<>\/\?][^!@$%^* =\[\]{};:\\|<>\?]*$

  • Related