【问题标题】:Regex/Python: Substitution in Python when the Regex already do the substitution正则表达式/Python:当正则表达式已经进行替换时,Python 中的替换
【发布时间】:2019-01-09 03:12:15
【问题描述】:

我正在尝试使用这个非常有效的正则表达式删除重复的行:

(.*+)\n*(\1\n+)* 

但是当我尝试在 Python 中使用它时它不起作用:

response1 = re.sub(r'(.*+)\n*', r'(\1\n+)*', response1)

错误:

Exception has occurred: re.error
multiple repeat at position 3

我做错了吗?

谢谢,

【问题讨论】:

  • 你也可以用[^\n]代替.来达到同样的效果
  • 我对量词和正则表达式本身都没有问题,我正在尝试让它在 Python 中工作
  • 所有格量词是的问题 - 原生 Python 不支持它们。
  • 删除所有格量词并使用[^\n] 而不是.。此外,替换字符串应该只是替换字符串(可能带有\ 组),而不是正则表达式。

标签: python regex


【解决方案1】:

“在位置 3 多次重复”问题与正则表达式有关:

.*+

您可以使用“.*”或“.+”。类似以下的内容应该删除连续的重复行:

response = """A
A    
A
B
B
A
A
"""
print(re.sub(r'(.*\n)(\1)+', r'\2', response))

输出

A
B
A

【讨论】:

  • 我使用了你的代码并得到了这个错误:预期的字符串或类似字节的对象
  • 可能“响应”不是字符串。什么是“响应”
猜你喜欢
  • 2012-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多