Python Regular Expression – Dot or Period

Spread the love

Dot or Period –

The dot ( . ) matches any single character except a newline character.

In [1]: import re

In [2]: text = '''Python is awesome
   ...: I love Python.'''

In [3]: re.findall('l..e', text)
Out[3]: ['love']

In [4]: re.findall('...e', text)
Out[4]: [' awe', 'some', 'love']

How to match a newline character ?

If you want dot (. ) to also match a newline character then you can use the re.DOTALL flag. This will match any single character including a newline character.

In [5]: re.findall('awesome.I', text)
Out[5]: []

In [6]: re.findall('awesome.I', text, flags=re.DOTALL)
Out[6]: ['awesome\nI']

How to match a Dot character ?

To match a dot character in a text, you have to escape the dot with a backslash.

In [7]: re.findall('Python.', text)
Out[7]: ['Python ', 'Python.']

In [8]: re.findall('Python\.', text)
Out[8]: ['Python.']

Rating: 1 out of 5.

Leave a Reply