在python中使用正则表达式删除带引号的双引号

时间:2020-04-08 21:57:28

标签: python regex regex-lookarounds

我正在尝试使用python中的正则表达式从文本中删除特定的双引号。我只想保留表示英寸的双引号。因此,这意味着在数字后留下任何双引号。

txt = 'measurement 1/2" and 3" "remove" end" a " multiple"""

预期输出: measurement 1/2" and 3" remove end a multiple

这是我最近的一个。

re.sub(r'[^(?!\d+/\d+")]"+', '', txt)

1 个答案:

答案 0 :(得分:2)

只需使用

(?<!\d)"+

请参见a demo on regex101.com


您的原始表情

[^(?!\d+/\d+")]

基本上不是(?!等。


另外,您可以将更新的regex模块与(*SKIP)(*FAIL)结合使用:

import regex as re

junk = '''measurement 1/2" and 3" "remove" end" a " multiple"""
ABC2DEF3"'''

rx = re.compile(r'\b\d(?:/\d+)?"(*SKIP)(*FAIL)|"+')

cleaned = rx.sub('', junk)
print(cleaned)

哪个会产生

measurement 1/2" and 3" remove end a  multiple
ABC2DEF3