Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negate characters in Regular Expression [closed]

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

  • No numbers
  • No special characters
  • No spaces

in a string

like image 844
nimi Avatar asked Nov 19 '09 12:11

nimi


People also ask

How do you negate a character in regex?

Similarly, the negation variant of the character class is defined as "[^ ]" (with ^ within the square braces), it matches a single character which is not in the specified or set of possible characters. For example the regular expression [^abc] matches a single character except a or, b or, c.

How can you negate characters in a set?

Negated Character Classes If you don't want a negated character class to match line breaks, you need to include the line break characters in the class. [^0-9\r\n] matches any character that is not a digit or a line break.

What does ?! Mean in regex?

It's a negative lookahead, which means that for the expression to match, the part within (?!...) must not match. In this case the regex matches http:// only when it is not followed by the current host name (roughly, see Thilo's comment). Follow this answer to receive notifications.


1 Answers

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.

like image 152
Steve Wortham Avatar answered Nov 16 '22 01:11

Steve Wortham