Python Regular Expression – Dollar ( $ ) – End of string

Spread the love

Dollar ( $ ) –

The Dollar sign is used to check if a string ends with certain characters.

In [1]: import re

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

In [3]: re.findall('\d+$', 'my number is 5382634519')
Out[3]: ['5382634519']

The first example search for a pattern in a string that ends with awesome and the second example search for a pattern that ends with digit characters.

Match end of each Line –

By default dollar sign matches the pattern at the end of the string. But if you want to match the pattern at the end of each line then you have to use the re.MULTILINE flag.

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

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

How to match a dollar sign?

To match a dollar sign you need to escape it using a backslash.

In [7]: re.findall('\$\d+', '$1000')
Out[7]: ['$1000']

First we escaped the dollar sign to remove it’s special meaning in regex. Then we used \d which matches any digit character and + matches one or more occurrences of the pattern to the left of it so it will match one or more digit characters.

Rating: 1 out of 5.

Leave a Reply