Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match literal string '\$'

I'm trying to match literal string '\$'. I'm escaping both '\' and '$' by backslash. Why isn't working when I escape the backslash in the pattern? But if I use a dot then it works.

import re

print re.match('\$','\$')
print re.match('\\\$','\$')
print re.match('.\$','\$')

Output:

None
None
<_sre.SRE_Match object at 0x7fb89cef7b90>

Can someone explain what's happening internally?

like image 315
Mohammad Yusuf Avatar asked Jul 22 '26 02:07

Mohammad Yusuf


1 Answers

You should use the re.escape() function for this:

escape(string)

Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.

For example:

import re
val = re.escape('\$') # val = '\\\$'
print re.match(val,'\$')

It outputs:

<_sre.SRE_Match object; span=(0, 2), match='\\$'>

This is equivalent to what @TigerhawkT3 mentioned in his answer.

like image 84
Wasi Ahmad Avatar answered Jul 24 '26 15:07

Wasi Ahmad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!