The Python function re.sub(pattern, replacement, string)
returns the modified string with the matched pattern replaced with the replacement. Is there any easy way to check whether a match has occurred and a modification has been made? (And also, how many modifications)
Asked
Active
Viewed 1,152 times
12
-
If performance is not an issue, you can check to see if the regex does any matches in the string before doing the sub. – Patashu May 29 '13 at 01:40
-
@Patashu That's true. What would be most efficient? (I'm not so familiar with Python regex). Would it be `if re.search(pattern, string) != None`? – Mika H. May 29 '13 at 01:43
1 Answers
14
Depends on the version. In Python <= 2.6, you have to couple sub()
with match()
or search()
to get count.
If you are using Python >= 2.7, you can use subn()
, which will return a tuple of (new_string, number_of_subs_made)
.
For example:
>>> import re
>>> re.subn('l', 'X', "Hello World!")
('HeXXo WorXd!', 3)

Tomerikoo
- 18,379
- 16
- 47
- 61

Andrew Sledge
- 10,163
- 2
- 29
- 30
-
Check that: it subn may have been in prior to 2.7. http://docs.python.org/2/library/re.html#re.subn – Andrew Sledge May 29 '13 at 01:48
-