python - 在 match.group 上重新订阅

标签 python regex

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/

相关文章:

python - 在 Pandas 中重命名列名

python - 一个对象在 Python 中创建了两次

regex - JavaScript 正则表达式中多个正向前瞻的语法

Javascript 正则表达式代码到 PHP 正则表达式?

php - 匹配 2-20 个字母数字字符的正则表达式,允许在字符串中的任何位置使用单个连字符

python - 试图让 django 应用程序在 CentOS 5 上与 mod_wsgi 一起工作

python - 如何判断imaplib2空闲响应是否是超时造成的

python - Python 的 AST 中的 ExtSlice 节点表示什么语法?

php - preg_replace 添加目标 ="_blank",但排除某些实例

php - 在 PHP 中使用正则表达式来验证名称