Regex to find out if the sequence has any special characters
I am looking for a regex to find out the given word sequence has any special characters.
For example.
In this input string
"test?test";
I would like to find out the words got
"test(any special char(s) inclu开发者_如何学Cding space)test"
You can just use [^A-Za-z0-9]
, which will match anything that is not alphanumeric, but of course it depends on what you consider a "special character." If underscore is not special [\W]
can be a shortcut for anything that is not a word (A-Za-z0-9_
) character.
You don't really need a regex here. If you want to test for alphanumeric characters, you car use LINQ, for example (or just iterate over the letters):
string input = "test test";
bool valid = input.All(Char.IsLetterOrDigit);
Char.IsLetterOrDigit
checks for all Unicode alphanumeric characters. If you only want the English ones, you can write:
public static bool IsEnglishAlphanumeric(char c)
{
return ((c >= 'a') && (c <= 'z'))
|| ((c >= 'A') && (c <= 'Z'))
|| ((c >= '0') && (c <= '9'));
}
and use it similarly:
bool valid = input.All(IsEnglishAlphanumeric);
精彩评论