I have a Javascript regex like this:
/^[a-zA-Z0-9 !@#$%^&*()-_-~. ,/\" ] $/
which allows following conditions:
only alphabets allowed
only numeric allowed
combination of alphabets and numeric allowed
combination of alphabets, numeric and special characters are allowed
I want to modify above regex with also cover one more case as below
only special characters are not allowed
string should not start with special characters
can someone please help me with this?
CodePudding user response:
You can require at least one alphanumeric:
/^(?=[^a-zA-Z0-9]*[a-zA-Z0-9])[a-zA-Z0-9 !@#$%^&*()_~. ,/\" -] $/
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Also, I think you wanted to match a literal -
, so need to repeat it, just escape, change -_-
to \-_
, or - better - move to the end of the character class.
The (?=[^a-zA-Z0-9]*[a-zA-Z0-9])
pattern is a positive character class that requires an ASCII letter of digit after any zero or more chars other than ASCII letters or digits, immediately to the right of the current location, here, from the start of string.