for element in f:
galcode_scan = re.search(ur'blah\.blah\.blah\(\'\w{5,10}', element)
如果我尝试执行 re.sub 并用其他东西删除废话并保留最后一位,则\w{5,10} 就会变成文字。如何保留该正则表达式 block 所占用的字符?
编辑:
这是完整的代码
for element in f:
galcode_scan = re.search(ur'Imgur\.Util\.triggerView\(\'\w{5,10}', element)
galcode_scan = re.sub(r'Imgur\.Util\.triggerView\(\'\w{5,10}', 'blah\.\w{5,10}', ur"galcode_scan\.\w{5,10}")
print galcode_scan
最佳答案
您可以使用正向先行 ((?=...)
) 在替换时不匹配,但作为整个模式匹配:
re.sub("blah\.blah\.blah\(\'(?=\w{5,10})", "", "blah.blah.blah('qwertyu")
'qwertyu'
如果你想替换你的匹配,只需将其添加到替换参数中即可:
re.sub("blah\.blah\.blah\(\'(?=\w{5,10})", "pref:", "blah.blah.blah('qwertyu")
'pref:qwertyu'
您还可以通过捕获模式 ((..)
) 并反向引用它 (\1
.. \9
>):
re.sub("blah\.blah\.blah\(\'(\w{5,10})", "pref:\\1", "blah.blah.blah('qwertyu")
'pref:qwertyu'
更新
所提供示例的更精确模式:
re.sub("Imgur\.Util\.triggerView'(?=\w{5,10})", "imgurl.com/", "Imgur.Util.triggerView'B1ahblA4")
'imgurl.com/B1ahblA4'
这里的模式是一个简单的字符串,因此无论您需要动态化什么,都可以使用变量。例如使用不同的映射:
map = {
'Imgur\.Util\.triggerView\'': 'imgurl.com/',
'Example\.Util\.triggerView\'': 'example.com/'
}
items = [
"Imgur.Util.triggerView'B1ahblA4",
"Example.Util.triggerView'FooBar"
]
for item in items:
for old, new in map.iteritems():
pattern = old + '(?=\w{5,10})'
if re.match(pattern, item):
print re.sub(pattern, new, item)
imgurl.com/B1ahblA4
example.com/FooBar
关于python - 在 match.group 上重新订阅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27575547/