I'm using regular expression -
/^[0-9a-zA-Z ~!@#$%^&*-_+=|?]*$/
to accept alphanumeric and some special characters for the string validation in JS. But, I don't want all string characters to be special characters only. Please suggest a valid regular expression for this case.
Thank you.
You could express your regex as:
^[0-9a-zA-Z ~!@#$%^&*-_+=|?]*[0-9a-zA-Z][0-9a-zA-Z ~!@#$%^&*-_+=|?]*$
This says to match at least one pure alphanumeric character, with optional other alphas or symbol characters.
^ start of the string
[0-9a-zA-Z ~!@#$%^&*-_+=|?]* match zero or more alphas or symbols
[0-9a-zA-Z] match one alphanumeric character
[0-9a-zA-Z ~!@#$%^&*-_+=|?]* match zero or more alphas or symbols
$ end of the string
For a slightly more terse regex, you could also use a positive lookahead:
^(?=.*[0-9a-zA-Z])[0-9a-zA-Z ~!@#$%^&*-_+=|?]*$
You can do it in several ways.
"any number of alphanumeric or special" followed by "alphanumeric" followed by "any number of alphanumeric or special" (asserts that there is at least one alphanumeric in there)
^[0-9a-zA-Z ~!@#$%^&*-_+=|?]*[0-9a-zA-Z][0-9a-zA-Z ~!@#$%^&*-_+=|?]*$
assert at the start "lookahead: any number of characters later, there will be an alphanumeric"
^(?=.*[0-9a-zA-Z])[0-9a-zA-Z ~!@#$%^&*-_+=|?]*$