Understanding Curly Braces in Regex

If we have a group that we want to repeat a specific number of times, follow the group in the regex with a number in curly brackets.

For example, the regex (Ha){3} will match the string ‘HaHaHa’, but it will not match ‘HaHa’, since the latter has only two repeats of the (Ha) group. Instead of just one number, you can specify a range in between the curly brackets. The regex (Ha){3, 5} will match ‘HaHaHa’, ‘HaHaHaHa’, and ‘HaHaHaHaHa’. You can also leave out the first or second number in the curly brackets to leave the minimum or maximum unbounded. (Ha){3, } will match three or more instances of the (Ha) group, while (Ha){, 5} will match zero to five instances. Curly brackets can help make your regular expressions shorter.

Example 1: In this example, we will use curly brackets to specify the occurrence of the pattern which we are looking for.

Python3




# Python program to illustrate
# Matching Specific Repetitions 
# with Curly Brackets
import re
haRegex = re.compile(r'(Ha){3}')
mo1 = haRegex.search('HaHaHa')
print(mo1.group())


Output:

HaHaHa

Example 2: In this example, we will define the occurrence of the pattern using curly brackets and then search for if a specific pattern exists in it or not.

Python3




# Python program to illustrate
# Matching Specific Repetitions 
# with Curly Brackets
import re
haRegex = re.compile(r'(Ha){3}')
mo2 = haRegex.search('Ha')== None
print(mo2)


Output:

True

Pattern matching in Python with Regex

You may be familiar with searching for text by pressing ctrl-F and typing in the words you’re looking for. Regular expressions go one step further: They allow you to specify a pattern of text to search for. In this article, we will see how pattern matching in Python works with Regex.

Similar Reads

Regex in Python

Regular expressions, also called regex, are descriptions of a pattern of text. It can detect the presence or absence of a text by matching it with a particular pattern and also can split a pattern into one or more sub-patterns. For example, a \d in a regex stands for a digit character — that is, any single numeral between 0 and 9....

Parentheses for Grouping and Capturing with Regex

...

Regular Expressions: Grouping and the Pipe Character

One of the ways of pattern matching with Regex is by using Parentheses around the patterns. Let us see a few different examples for a better understanding....

Understanding Curly Braces in Regex

...

Optional Operator or question mark (?) in Regular Expression

...

Zero or More Pattern Matching with the Star

...

One or More Pattern Matching with the Plus

The | character is called a pipe. We can use it anywhere we want to match one of many expressions....