Python Regular Expression – Question mark ( ? ) quantifier

Spread the love

Question mark quantifier –

The question mark quantifier matches zero or one occurrences of the pattern to the left of it.

In [1]: import re

In [2]: re.findall('python?', 'pytho')
Out[2]: ['pytho']

In [3]: re.findall('python?', 'python')
Out[3]: ['python']

In [4]: re.findall('python?', 'pythonnnn')
Out[4]: ['python']

The question mark ( ? ) in ‘python?’ will match zero or one occurrences of n as n is to the left of it.

Let’s say that you want to match http as well as https, you can use the question mark quantifier.

In [5]: re.findall('https?', 'http , https')
Out[5]: ['http', 'https']

Or you may want to match color or colour as people use both.

In [6]: re.findall('colou?r', 'color, colour')
Out[6]: ['color', 'colour']

How to match a question mark character ?

If you want to match a question mark character then escape the question mark with a backslash.

In [7]: re.findall('\?' , 'How are you?')
Out[7]: ['?']

Rating: 1 out of 5.

Leave a Reply