python re.sub的行为与re.search不一致
我有一段代码,我正在尝试进行一些搜索和替换。我的代码通常按预期工作,但我遇到了一个违背我预期的用例。在这个有问题的例子中,我有python re.sub的行为与re.search不一致,python,regex,Python,Regex,我有一段代码,我正在尝试进行一些搜索和替换。我的代码通常按预期工作,但我遇到了一个违背我预期的用例。在这个有问题的例子中,我有 input_regex = 'Cooper S \\(3doors\\)' subst_regex = 'Cooper S Hardtop 2 Door' 最初 input_text = 'cooper s (3doors)' 我的代码片段: matchobject = re.search(input_regex,input_text,re.IGNORECASE)
input_regex = 'Cooper S \\(3doors\\)'
subst_regex = 'Cooper S Hardtop 2 Door'
最初
input_text = 'cooper s (3doors)'
我的代码片段:
matchobject = re.search(input_regex,input_text,re.IGNORECASE)
if matchobject:
input_text=re.sub(input_regex,subst_regex,input_text,re.IGNORECASE)
我希望输入文本更改为
'Cooper S Hardtop 2 Door'
当我完成后,它将保持不变,尽管我已经确认确实从
re.search
创建了一个匹配对象。如果对input\u text
执行re.search
搜索input\u regex
成功,为什么re.sub
不能找到相同的匹配项并进行替换?始终对regex模式使用原始字符串。re.sub
的第四个参数不是标志。因此,在调用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'
>>输入\u regex=r'Cooper S\(3doors\)'
>>>重新搜索(输入正则表达式、输入文本、重新忽略案例)
>>>re.sub(input_regex,subst_regex,input_text,flags=re.IGNORECASE)
“库珀硬顶2门”
您可以选择regex
方式:
import re
input_text = 'cooper s (3doors)'
input_regex = '\(3doors\)'
subst_regex = 'Hardtop 2 Door'
print(re.sub(input_regex, subst_regex, input_text))
print(input_text.replace('(3doors)', 'Hardtop 2 Door'))
或者只是一种非regex方式:
import re
input_text = 'cooper s (3doors)'
input_regex = '\(3doors\)'
subst_regex = 'Hardtop 2 Door'
print(re.sub(input_regex, subst_regex, input_text))
print(input_text.replace('(3doors)', 'Hardtop 2 Door'))
这样做:
import re
input_regex = re.compile("\\(3doors\\)", re.IGNORECASE)
subset_regex = "Hardtop 2 Door"
input_text = "cooper s (3doors)"
result = input_regex.sub(subset_regex, input_text)
跳过进行重新搜索的部分。不需要。结果是:
cooper s Hardtop 2 Door
注意:不要在正则表达式变量中给出整个文本。这没用。这不是regex的工作方式我能够从re.search函数生成相同的匹配对象。我的问题是,当我继续运行re.sub时,它没有找到相同的匹配项来进行替换。更新了答案!这是因为re.IGNORECASE处于错误的位置,无法成为位置论点。将其更改为关键字参数“flags=re.IGNORECASE”修复了我的问题。谢谢