Inverting character sets in regular expressions in JavaScript
With the hat '^'
at the beginning of
the square brackets, you can invert what you
want. That is, if, for example, the command
[ab]
looks for the letter 'a'
or 'b'
, then the command [^ab]
will look for all characters except 'a'
and 'b'
.
Example
In this example, the search pattern looks like
this: letter 'x'
, then NOT the letter
'a'
, not 'b'
and not 'c'
,
then letter 'z'
:
let str = 'xaz xbz xcz xez';
let res = str.replace(/x[^abc]z/g, '!');
As a result, the following will be written to the variable:
'xax xbx xcx !'
Example
In this example, the search pattern looks like
this: letter 'x'
, then NOT a small
Latin letter, then letter 'z'
:
let str = 'xaz xbz x1z xСz';
let res = str.replace(/x[^a-z]z/g, '!');
As a result, the following will be written to the variable:
'xaz xbz ! !'
Practical tasks
Write a regex that matches strings with
the pattern: digit '1'
, then
not character 'e'
and not 'x'
,
digit '2'
.
Write a regex that matches strings with a
pattern: letter 'x'
, then NOT a
digit from 2
to 7
, letter
'z'
.
Write a regex that matches strings with a
pattern: letter 'x'
, then NOT a
capital Latin letter 1
and more
times, letter 'z'
.
Write a regex that matches strings with a
pattern: letter 'x'
, then NOT a
capital or small Latin letter and not a digit
from 1
to 5
- 1
and
more times, letter 'z'
.