Curly braces in regular expressions in JavaScript
The '+'
, '*'
, '?'
operators
are nice, but they cannot be used to specify a
certain number of repetitions. In this case,
the operator {}
will come to your aid.
It works as follows: {5}
- five repetitions,
{2,5}
- repeats from two to five times (both
inclusive), {2,}
- repeats two or more times.
Please note that there is no such option - {,2}
.
See examples:
Example
In this example, the search pattern looks like this:
letter 'x'
, letter 'a'
once or twice,
letter 'x'
:
let str = 'xx xax xaax xaaax';
let res = str.replace(/xa{1,2}x/g, '!');
As a result, the following will be written to the variable:
'xx ! ! xaaax'
Example
In this example, the search pattern looks like
this: letter 'x'
, letter 'a'
two or more times, letter 'x'
:
let str = 'xx xax xaax xaaax';
let res = str.replace(/xa{2,}x/g, '!');
As a result, the following will be written to the variable:
'xx xax ! !'
Example
In this example, the search pattern looks like
this: letter 'x'
, letter 'a'
three times, letter 'x'
:
let str = 'xx xax xaax xaaax';
let res = str.replace(/xa{3}x/g, '!');
As a result, the following will be written to the variable:
'xx xax xaax !'
Example
In this example, the search pattern looks like
this: letter 'a'
ten times:
let str = 'aaa aaaaaaaaaa aaa';
let res = str.replace(/a{10}/g, '!');
As a result, the following will be written to the variable:
'aaa ! aaa'
Example
In this example, the code author wanted this pattern:
letter 'x'
, letter 'a'
three times or
less, letter 'x'
, but, unfortunately,
this - {,3} - does not work. It must be specified
explicitly:
let str = 'xx xax xaax xaaax';
let res = str.replace(/xa{1,3}x/g, '!');
As a result, the following will be written to the variable:
'xx ! ! !'
Example
Zero is also allowed:
let str = 'xx xax xaax xaaax';
let res = str.replace(/xa{0,3}x/g, '!');
As a result, the following will be written to the variable:
'! ! ! !'
Practical tasks
Given a string:
let str = 'aa aba abba abbba abbbba abbbbba';
Write a regex that matches only
the strings 'abba'
, 'abbba'
,
'abbbba'
.
Given a string:
let str = 'aa aba abba abbba abbbba abbbbba';
Write a regex that matches the strings
like 'aba'
where 'b'
occurs less than
3
times (inclusive).
Given a string:
let str = 'aa aba abba abbba abbbba abbbbba';
Write a regex that matches the strings
like 'aba'
where 'b'
occurs more than
4
times (inclusive).