Reputation: 1403
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 to cover two more cases as below:
only special characters are not allowed
string should not start with special characters
so basicaly my requirement is:
string = 'abc' -> Correct
string = '123' -> Correct
string = 'abc123' ->Correct
string = 'abc123!@#' ->Correct
string = 'abc!@#123' -> Correct
string = '123!@#abc' -> Correct
string = '!@#' -> Wrong
string = '!@#abc' -> Wrong
string = '!@#123' -> Wrong
string = '!@#abc123' -> Wrong
can someone please help me with this?
Upvotes: 2
Views: 1472
Reputation: 99
If all the special characters are allowed and you consider that underscore _
is also a special character then you can always simplify your RegEx like this :
/^[^\W_].+$/
Check here for your given examples on Regex101
Upvotes: 0
Reputation: 43870
Just add [a-zA-Z0-9]
to the beginning of the regex:
/^[a-zA-Z0-9][a-zA-Z0-9 \^\\\-!@#$%&*()_~.+,/'"]+$/gm
Note, if within a class (ie [
...]
) that there are four special characters that must be escaped by prefixing a backward slash (\
) to it so that it is interpreted as it's literal meaning:
// If within a class (ie [...])
^ \ - ]
// If not within a class
\ ^ $ . * + ? ( ) [ ] { } |
Upvotes: 0
Reputation: 626728
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.
Upvotes: 1