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.