Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

re.sub not replacing the string

Is there a mistake in the below code?

import re
text = 'AFL_v_CalcOneIntAreas (%as_Points[0].ub_X%);\n'

print(re.sub('as_Points[0].ub_X', '0x00', text))

The expected output is

AFL_v_CalcOneIntAreas (%0x00%);

but the actual output is same as input string, please let me know why is it behaving like this?

like image 878
Bharadwaj Avatar asked May 13 '26 17:05

Bharadwaj


2 Answers

You should escape [, ] and .:

>>> re.sub('as_Points\[0\]\.ub_X', '0x00', text)

. means "any character", [0] matches only "0".

You can do this as well:

esc = re.escape('as_Points[0].ub_X')  # now '[0]' is treated like the string
                                      # literal '[0]' and not the regex '[0]'
re.sub(esc, '0x00', text)

Visit the re module for more useful functions.

like image 147
Maroun Avatar answered May 15 '26 07:05

Maroun


The symbols [ and ] means something in regular expressions, you have to escape them:

>>> re.sub('as_Points\[0\]\.ub_X', '0x00', text)
'AFL_v_CalcOneIntAreas (%0x00%);\n'

[a-z] represents all the lower letters for instance. [...] are used to denote «anything in them» so [01] is for 0 or 1.
In your case 'as_Points[0].ub_X' is in fact 'as_Points0.ub_X'.

Note that the . has special meanings too. It means 1 character. You should also escape it too.


If you don't know if your expression contains characters you should escape, you can use re.escape:

>>> someExpression = "as_Points[0].ub_X"
>>> re.escape(someExpression)
'as\\_Points\\[0\\]\\.ub\\_X'
>>> re.sub(re.escape(someExpression), '0x00', text)
'AFL_v_CalcOneIntAreas (%0x00%);\n'

But if you don't need regular expression power, strings have the replace method:

text.replace('as_Points[0].ub_X','0x00')
like image 22
fredtantini Avatar answered May 15 '26 06:05

fredtantini



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!