简体   繁体   中英

Regex Expressions for all non alphanumeric symbols

I am trying to make a regular expression for a string that has at least 1 non alphanumeric symbol in it

The code I am trying to use is

Regex symbolPattern = new Regex("?[!@#$%^&*()_-+=[{]};:<>|./?.]");

I'm trying to match only one of !@#$%^&*()_-+=[{]};:<>|./?. but it doesn't seem to be working.

If you want to match non-alphanumeric symbols then just use \\W|_ .

Regex pattern = new Regex(@"\W|_");

This will match anything except 0-9 and az. Information on the \\W character class and others available here (c# Regex Cheet Sheet).

如果需要,还可以避免使用正则表达式:

return s.Any(c => !char.IsLetterOrDigit(c))

Can you check for the opposite condition?

Match match = Regex.Match(@"^([a-zA-Z0-9]+)$");
if (!match.Success) {
    // it's alphanumeric
} else {
    // it has one of those characters in it.
}

I didn't get your entire question, but this regex will match those strings that contains at least one non alphanumeric character. That includes whitespace (couldn't see that in your list though)

[^\w]+

Your regex just needs little tweaking. The hyphen is used to form ranges like AZ , so if you want to match a literal hyphen, you either have to escape it with a backslash or move it to the end of the list. You also need to escape the square brackets because they're the delimiters for character class. Then get rid of that question mark at the beginning and you're in business.

Regex symbolPattern = new Regex(@"[!@#$%^&*()_+=\[{\]};:<>|./?,-]");

If you only want to match ASCII punctuation characters, this is probably the simplest way. \\W matches whitespace and control characters in addition to punctuation, and it matches them from the entire Unicode range, not just ASCII.

You seem to be missing a few characters, though: the backslash, apostrophe and quotation mark. Adding those gives you:

@"[!@#$%^&*()_+=\[{\]};:<>|./?,\\'""-]"

Finally, it's a good idea to always use C#'s verbatim string literals ( @"..." ) for regexes; it saves you a lot of hassle with backslashes. Quotation marks are escaped by doubling them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM