Python Forum
Who enjoys Py RegEx? re.sub() isn't working
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Who enjoys Py RegEx? re.sub() isn't working
#4
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 !
Reply


Messages In This Thread
RE: Who enjoys Py RegEx? re.sub() isn't working - by goodsignal - Jun-08-2020, 05:49 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Regex to extract IPs between () not working mrapple2020 5 3,592 Apr-12-2019, 08:03 AM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020