Negate characters in Regular Expression

RegexRegex Negation

Regex Problem Overview


How would I write a regular expression that matches the following criteria?

  • No numbers
  • No special characters
  • No spaces

in a string

Regex Solutions


Solution 1 - Regex

The caret inside of a character class [^ ] is the negation operator common to most regular expression implementations (Perl, .NET, Ruby, Javascript, etc). So I'd do it like this:

[^\W\s\d]
  • ^ - Matches anything NOT in the character class
  • \W - matches non-word characters (a word character would be defined as a-z, A-Z, 0-9, and underscore).
  • \s - matches whitespace (space, tab, carriage return, line feed)
  • \d - matches 0-9

Or you can take another approach by simply including only what you want:

[A-Za-z]

The main difference here is that the first one will include underscores. That, and it demonstrates a way of writing the expression in the same terms that you're thinking. But if you reverse you're thinking to include characters instead of excluding them, then that can sometimes result in an easier to read regular expression.

It's not completely clear to me which special characters you don't want. But I wrote out both solutions just in case one works better for you than the other.

Solution 2 - Regex

In Perl, it would be something like:

$string !~ /[\d \W]/

Of course, it depends on your definition of "special characters". \W matches all non-word characters. A word character is any alphanumeric character plus the space character.

Solution 3 - Regex

Try ^[^0-9\p{P} ]$

Solution 4 - Regex

var StringInputToClean = @"[:(M)?*a',\y<>&a#~%{}+.@\\ /27!;$+]";

var pattern = @"[^a-zA-Z0-9\s]";

string replacement = "";

var result = Regex.Replace(StringInputToClean, pattern, replacement);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnimiView Question on Stackoverflow
Solution 1 - RegexSteve WorthamView Answer on Stackoverflow
Solution 2 - RegexThomas OwensView Answer on Stackoverflow
Solution 3 - RegexPaul McLeanView Answer on Stackoverflow
Solution 4 - RegexleiView Answer on Stackoverflow