Python Regular Expression – curly braces

Spread the love

curly braces –

Curly braces matches exactly the specified number of occurrences.

P{2} will match P exactly two times. P{2,3} will match P at least 2 times but not more than 3 times.

Let’s say you want to find all the phone numbers from a text.

In [1]: import re
In [2]: re.findall('\+\d{2}-\d{10}', '+91-7239312893 +91-3754296102')
Out[2]: ['+91-7239312893', '+91-3754296102']

The \+ say that the numbers starts with a plus character. As plus is a special character in regex we escaped it with a backslash to remove the special meaning from it. \d matches any digit character between 0 to 9, and \d{2} matches with any two digits. Then we have a hyphen followed by \d{10} which matches exactly 10 digits.

In [3]: re.findall('hello{2,3}', 'hello')
Out[3]: []

In [4]: re.findall('hello{2,3}', 'helloo')
Out[4]: ['helloo']

In [5]: re.findall('hello{2,3}', 'helloooo')
Out[5]: ['hellooo']

The pattern ‘hello{2,3}’ will match any hello which has os between 2 to 3 at the end. The first example does not have at least 2 os that is why we got an empty list.

Rating: 1 out of 5.

Leave a Reply