Repetition operators in regex

There are situations where we want to specify that a character is repeated a given number of times. If we know the exact number of repetitions, then we can simply write it several times - /aaaa/. But what if we want to say something like this: repeat one or more times?

There are repetition operators (quantifiers) for this: plus sign + (one or more times), star * (zero or more times) and question mark ? (zero or one time). These operators act on the character that precedes them.

Let's see how these operators work with examples.

Example

Let's find all substrings matching the given pattern letter 'x', letter 'a' one or more times, letter 'x'⁅/r]:

let str = 'xx xax xaax xaaax xbx'; let res = str.replace(/xa+x/g, '!');

As a result, the following will be written to the variable:

'xx ! ! ! xbx'

Example

Let's find all substrings matching the pattern letter 'x', letter 'a' zero or more times, letter 'x'⁅/r]:

let str = 'xx xax xaax xaaax xbx' let res = str.replace(/xa*x/g, '!');

As a result, the following will be written to the variable:

'! ! ! ! xbx'

Example

Find all substrings matching the given pattern letter 'x', letter 'a' zero or one time, letter 'x'⁅/r]:

let str = 'xx xax xaax xbx'; let res = str.replace(/xa?x/g, '!');

As a result, the following will be written to the variable:

'! ! xaax xbx'

Practical tasks

Given a string:

let str = 'aa aba abba abbba abca abea';

Write a regex that matches the 'aba', 'abba', 'abbba' strings using the pattern: letter 'a', letter 'b' any number of times, letter 'a'.

Given a string:

let str = 'aa aba abba abbba abca abea';

Write a regex that matches the 'aa', 'aba', 'abba', 'abbba' strings by pattern: letter 'a', letter 'b' any number of times (including none times), letter 'a'.

Given a string:

let str = 'aa aba abba abbba abca abea';

Write a regex that matches the 'aa', 'aba' strings using the pattern: letter 'a', letter 'b' once or none, letter 'a'.

Given a string:

let str = 'aa aba abba abbba abca abea';

Write a regex that matches the 'aa', 'aba', 'abba', 'abbba' strings, without capturing 'abca' and 'abea'.

enru