Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether modification in re.sub occurred

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)

like image 389
Mika H. Avatar asked May 29 '13 01:05

Mika H.


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.

WHAT IS RE sub () 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.

How do you replace re subs?

If you want to replace a string that matches a regular expression (regex) instead of perfect match, use the sub() of the re module. In re. sub() , specify a regex pattern in the first argument, a new string in the second, and a string to be processed in the third.

What is count in re sub?

The count argument will set the maximum number of replacements that we want to make inside the string. By default, the count is set to zero, which means the re. sub() method will replace all pattern occurrences in the target string.


1 Answers

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)
like image 76
Andrew Sledge Avatar answered Oct 07 '22 11:10

Andrew Sledge