Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which regular expression operator means 'Don't' match this character?

Tags:

regex

*, ?, + characters all mean match this character. Which character means 'don't' match this? Examples would help.

like image 832
Ali Avatar asked May 08 '11 05:05

Ali


People also ask

How do I not match a character in regex?

To replace or remove characters that don't match a regex, call the replace() method on the string passing it a regular expression that uses the caret ^ symbol, e.g. /[^a-z]+/ .

Which operator is used to match character?

LIKE operator is used for pattern matching, and it can be used as -. % – It matches zero or more characters.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

Which pattern is used to match any non What character?

All the characters other than the English alphabet (both cases) and, digits (0 to 9) are considered as non-word characters. You can match them using the meta character “\W”.


2 Answers

You can use negated character classes to exclude certain characters: for example [^abcde] will match anything but a,b,c,d,e characters.

Instead of specifying all the characters literally, you can use shorthands inside character classes: [\w] (lowercase) will match any "word character" (letter, numbers and underscore), [\W] (uppercase) will match anything but word characters; similarly, [\d] will match the 0-9 digits while [\D] matches anything but the 0-9 digits, and so on.

If you use PHP you can take a look at the regex character classes documentation.

like image 137
Paolo Stefan Avatar answered Sep 24 '22 19:09

Paolo Stefan


There's two ways to say "don't match": character ranges, and zero-width negative lookahead/lookbehind.

The former: don't match a, b, c or 0: [^a-c0]

The latter: match any three-letter string except foo and bar:

(?!foo|bar).{3}

or

.{3}(?<!foo|bar)

Also, a correction for you: *, ? and + do not actually match anything. They are repetition operators, and always follow a matching operator. Thus, a+ means match one or more of a, [a-c0]+ means match one or more of a, b, c or 0, while [^a-c0]+ would match one or more of anything that wasn't a, b, c or 0.

like image 45
Amadan Avatar answered Sep 25 '22 19:09

Amadan