⊗ppPmRgRO 224 of 447 menu

Character Repetition Operators in Regex

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

For this, there are (quantifiers) repetition operators: plus + (one or more times), asterisk * (zero or more times) and question mark ? (zero or one time). These operators act on the character that stands before them.

Let's look at the work of these operators with examples.

Example

Let's find all substrings matching the pattern letter 'x', letter 'a' one or more times, letter 'x':

<?php $str = 'xx xax xaax xaaax xbx'; $res = preg_replace('#xa+x#', '!', $str); ?>

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':

<?php $str = 'xx xax xaax xaaax xbx'; $res = preg_replace('#xa*x#', '!', $str); ?>

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

'! ! ! ! xbx'

Example

Let's find all substrings matching the pattern letter 'x', letter 'a' zero or one time, letter 'x':

<?php $str = 'xx xax xaax xbx'; $res = preg_replace('#xa?x#', '!', $str); ?>

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

'! ! xaax xbx'

Practice Tasks

Given a string:

<?php $str = 'aa aba abba abbba abca abea'; ?>

Write a regex that will find strings matching the pattern: letter 'a', letter 'b' one or more times, letter 'a'.

Given a string:

<?php $str = 'aa aba abba abbba abca abea'; ?>

Write a regex that will find strings matching the pattern: letter 'a', letter 'b' zero or more times, letter 'a'.

Given a string:

<?php $str = 'aa aba abba abbba abca abea'; ?>

Write a regex that will find strings matching the pattern: letter 'a', letter 'b' one time or none, letter 'a'.

Given a string:

<?php $str = 'aa aba abba abbba abca abea'; ?>

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

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline