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()
?
Asked
Active
Viewed 8,398 times
28

Cœur
- 37,241
- 25
- 195
- 267

prashantb j
- 403
- 4
- 10
-
Why wouldn't it replace correctly. You can check the string for the regex with `re.match()`before if you want to know if there are any matches inside. – nipeco Dec 13 '15 at 17:58
-
2I assumed the question meant: "how can you tell if re.sub() makes substitutions or not" – Jon Dec 13 '15 at 18:02
-
What are you actually trying to do? – Padraic Cunningham Dec 13 '15 at 18:06
-
1@Padraic : thought of printing message like "substitution success" after validating re.sub() in a "if" condition. – prashantb j Dec 14 '15 at 16:31
2 Answers
8
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.

ivan_pozdeev
- 33,874
- 19
- 107
- 152

Jon
- 1,122
- 8
- 10
-
3Cannot understand the downvotes. I confirmed this to work. This is even documented: "If the pattern isn’t found, string is returned unchanged". Well, it doesn't explicitly say "the same object", so it _might_ break sometime, but if the OP is dead set on avoiding comparison, this is the best we can offer. – ivan_pozdeev Dec 13 '15 at 18:01
-
1`re.sub(s1, "a", "b")` makes no sense in the context of your answer – Padraic Cunningham Dec 13 '15 at 18:07
-
1
-
2Well, didn't know about `subn` in the other answer (because I didn't ever need it), that one is definitely the "one obvious way". This one is still worthy of the "second prize". – ivan_pozdeev Dec 13 '15 at 18:15