*, ?, +
characters all mean match this character. Which character means 'don't' match this? Examples would help.
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]+/ .
LIKE operator is used for pattern matching, and it can be used as -. % – It matches zero or more characters.
$ means "Match the end of the string" (the position after the last character in the string).
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”.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With