Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if re.sub() has successfully replaced in python? [duplicate]

Tags:

python

regex

Since re.sub() returns the whole modified/unmodified string, is there any way to check if re.sub() has successfully modified the text, without searching the output of re.sub()?

like image 966
prashantb j Avatar asked Dec 13 '15 17:12

prashantb j


People also ask

What does re sub () do?

re. sub() function is used to replace occurrences of a particular sub-string with another sub-string. This function takes as input the following: The sub-string to replace.

How does re sub work in Python?

sub() function belongs to the Regular Expressions ( re ) module in Python. It returns a string where all matching occurrences of the specified pattern are replaced by the replace string.


2 Answers

You can use re.subn which perform the same operation as sub(), but return a tuple (new_string, number_of_subs_made)

If number of modification is 0 i.e. string is not modified.

>>> re.subn('(xx)+', '', 'abcdab')
('abcdab', 0)
>>> re.subn('(ab)+', '', 'abcdab')
('cd', 2)
>>> 
like image 190
Praveen Avatar answered Sep 21 '22 16:09

Praveen


If you have the following code:

import re
s1 = "aaa"
result = re.sub("a", "b", s1)

You can check if the call to sub made subsitutions by comparing the id of result to s1 like so:

id(s1) == id(result)

or, which is the same:

s1 is result

This is because strings in python are immutable, so if any substitutions are made, the result will be a different string than the original (ie: the original string is unchanged). The advantage of using the ids for comparison rather than the contents of the strings is that the comparison is constant time instead of linear.

like image 30
Jon Avatar answered Sep 19 '22 16:09

Jon