Reputation: 10575
/^[^ ]([\w- \.\\\/&#]+)[^ ]$/,
I have the above regex. I want to make sure it accepts all special characters but i don't want to specify the entire special character listsuch as [\w- \.\\\/&#!@#$&]
. How can we make sure the above regex accepts all special characters
Upvotes: 2
Views: 10894
Reputation: 75232
Since you've got \w
and a space in there already, you must want all of the ASCII characters except control characters. That would be:
[ -~]
...or any character whose code point is in the range U+0020
(space) to U+007E
(tilde). But it looks like you want to make sure the first and last characters are not whitespace. In fact, looking at your previous question, I'll assume you want only letters or digits in those positions. This would work:
/^[A-Za-z0-9][ -~]*[A-Za-z0-9]$/
...but that requires the string to be at least two characters long. To allow for a single-character string, change it to this:
/^[A-Za-z0-9](?:[ -~]*[A-Za-z0-9])?$/
In other words, if there's only one character, it must be a letter or digit. If there are two or more characters, the first and last must letters or digits, while the rest can be any printing character--i.e., a letter, a digit, a "special" (punctuation) character, or a space.
Note that this only matches ASCII characters, not accented Latin letters like Â
or ë
, or symbols from other alphabets or writing systems.
Upvotes: 1
Reputation: 336198
[^\w\s]
matches any non-alphanumeric and non-whitespace character.
\S
matches any non-whitespace character.
.
matches any character except newlines.
[\S\s]
matches any character in a JavaScript regex.
Upvotes: 7