Python Regular Expression – Caret ( ^ ) – start of string

Spread the love

Caret ( ^ ) –

The caret symbol is used to check if a string starts with a certain character.

In [1]: import re

In [2]: re.findall('^python', 'python is awesome')
Out[2]: ['python']

In [3]: re.findall('^python', 'I love python')
Out[3]: []

In both the examples we are looking for a string that starts with python. In the first example the string starts with python so we got match. In the second example, although python is there but we do not get any match as python is not at the beginning of a string.

Match at a Start of each line –

By default the caret symbol matches the pattern at the beginning of a string. But if you want to match the pattern at the beginning of each newline in a multi line string then you have to use the re.MULTILINE flag.

In [4]: text = '''python is awesome.
   ...: python is growing very fast.'''

In [5]: re.findall('^python', text)
Out[5]: ['python']

In [6]: re.findall('^python', text, flags=re.MULTILINE)
Out[6]: ['python', 'python']

Rating: 1 out of 5.

Leave a Reply