Issue
I have a section of code where I'm trying to do some search and replace. My code usually works as expected, but I'm encountering a use case that defies my expectations. In the problematic example, I have
input_regex = 'Cooper S \\(3doors\\)'
subst_regex = 'Cooper S Hardtop 2 Door'
and initially
input_text = 'cooper s (3doors)'
My code fragment:
matchobject = re.search(input_regex,input_text,re.IGNORECASE)
if matchobject:
input_text=re.sub(input_regex,subst_regex,input_text,re.IGNORECASE)
I am expecting input_text to be changed to
'Cooper S Hardtop 2 Door'
when I'm done, but instead it's unchanged, even though I have confirmed that a Matchobject is indeed created from the re.search
. If doing a re.search
for input_regex
on input_text
was successful, why wouldn't the re.sub
find the same match and make the replacement?
Solution
Always use raw string for regex pattern. And 4th arg for re.sub
is not flags. So make sure you specify the flags=re.IGNORECASE
while invoking re.sub
>>> input_regex = r'Cooper S \(3doors\)'
>>> re.search(input_regex,input_text,re.IGNORECASE)
<re.Match object; span=(0, 17), match='cooper s (3doors)'>
>>> re.sub(input_regex,subst_regex,input_text, flags=re.IGNORECASE)
'Cooper S Hardtop 2 Door'
Answered By - Sunitha
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.