Jun-08-2020, 05:49 AM
This perspective brings everything together! Thank you! The behavior makes complete sense now that I understand the nuance between re.sub() and the combination of re.search() and re.groups()
Just to summarize in my own words:
re.search() will return the extent of the pattern match, which could be a sub-string of the input.
re.sub() will return the entire input, only replacing the portion that matches the regex pattern.
When working line-by-line, as is often done in python, it's possible to make re.search() behave like re.sub() by matching the entirety of every line then and modify the line by strategic captured group management.
And it's possible to make re.sub() and re.search provide the same results with the same regex pattern, but the two approaches might require different captured group pattern management to respectively produce the same results.
The two can accomplish the same thing, but their approaches are different. Forcing one to act like the other requires more work. Understanding the difference will lead to choosing the tool with a more efficient approach.
Thanks again @bowlofred !
Just to summarize in my own words:
re.search() will return the extent of the pattern match, which could be a sub-string of the input.
re.sub() will return the entire input, only replacing the portion that matches the regex pattern.
When working line-by-line, as is often done in python, it's possible to make re.search() behave like re.sub() by matching the entirety of every line then and modify the line by strategic captured group management.
And it's possible to make re.sub() and re.search provide the same results with the same regex pattern, but the two approaches might require different captured group pattern management to respectively produce the same results.
The two can accomplish the same thing, but their approaches are different. Forcing one to act like the other requires more work. Understanding the difference will lead to choosing the tool with a more efficient approach.
Thanks again @bowlofred !