Python Regex 引擎 - “后视需要固定宽度模式”错误
- 2025-02-11 09:51:00
- admin 原创
- 52
问题描述:
我正在尝试处理 CSV 格式的字符串内不匹配的双引号。
确切地说,
"It "does "not "make "sense", Well, "Does "it"
应更正为
"It" "does" "not" "make" "sense", Well, "Does" "it"
所以基本上我想做的是
替换所有“”
前面没有行首或逗号(和)
后面没有逗号或行尾
和 ' ” ” '
为此我使用以下正则表达式
(?<!^|,)"(?!,|$)
问题是,虽然 Ruby 正则表达式引擎(http://www.rubular.com/)能够解析正则表达式,但 python 正则表达式引擎(https://pythex.org/、http://www.pyregex.com/ )会抛出以下错误
Invalid regular expression: look-behind requires fixed-width pattern
使用 python 2.7.3 时会抛出
sre_constants.error: look-behind requires fixed-width pattern
有人能告诉我这里有什么让 Python 恼火的事情吗?
编辑:
根据 Tim 的回复,我得到了以下多行字符串的输出
>>> str = """ "It "does "not "make "sense", Well, "Does "it"
... "It "does "not "make "sense", Well, "Does "it"
... "It "does "not "make "sense", Well, "Does "it"
... "It "does "not "make "sense", Well, "Does "it" """
>>> re.sub(r's*"(?!,|$)', '" "', str)
' "It" "does" "not" "make" "sense", Well, "Does" "it" "
"It" "does" "not" "make" "sense", Well, "Does" "it" "
"It" "does" "not" "make" "sense", Well, "Does" "it" "
"It" "does" "not" "make" "sense", Well, "Does" "it" " '
在每一行的末尾,在“it”旁边添加了两个双引号。
因此我对正则表达式做了很小的改动来处理换行符。
re.sub(r's*"(?!,|$)', '" "', str,flags=re.MULTILINE)
但这给出了输出
>>> re.sub(r's*"(?!,|$)', '" "', str,flags=re.MULTILINE)
' "It" "does" "not" "make" "sense", Well, "Does" "it"
... "It" "does" "not" "make" "sense", Well, "Does" "it"
... "It" "does" "not" "make" "sense", Well, "Does" "it"
... "It" "does" "not" "make" "sense", Well, "Does" "it" " '
仅最后一个“it”就有两个双引号。
但是我想知道为什么行尾字符“$”不能标识该行已经结束。
最终答案是
re.sub(r's*"(?!,|[ ]*$)', '" "', str,flags=re.MULTILINE)
解决方案 1:
Python 后re
视确实需要固定宽度,并且当后视模式中的交替长度不同时,有几种方法可以处理这种情况:
重写模式,这样您就不必使用交替(例如,Tim 的上述答案使用单词边界,或者您也可以使用
(?<=[^,])"(?!,|$)
当前模式的完全等价物,该模式需要在双引号前使用逗号以外的字符,或者使用常用模式来匹配用空格括起来的单词,,(?<=s|^)w+(?=s|$)
可以写成(?<!S)w+(?!S)
),或者拆分后视:
正向后视需要在组中交替进行(例如,
(?<=a|bc)
应重写为(?:(?<=a)|(?<=bc))
)如果后视模式是锚点与单个字符的交替,则可以反转后视的符号并使用包含字符的否定字符类。例如,
(?<=s|^)
匹配空格或字符串/行的开头(如果re.M
使用)。因此,在 Python 中re
,使用(?<!S)
。(?<=^|;)
将转换为(?<![^;])
。并且,如果您还想确保行的开头也匹配,请添加`到否定字符类,例如
(?<![^;
])(请参阅Python Regex:匹配行首、分号或字符串开头,无捕获组
(?<!S))。注意,由于
S`不匹配换行符,因此没有必要这样做。
+ 负向后视可以直接连接起来(例如`(?<!^|,)"(?!,|$)`看起来像`(?<!^)(?<!,)"(?!,|$)`)。
或者,只需使用(或) 安装PyPi 正则表达式模块并享受无限宽度后视。pip install regex
`pip3 install regex`
解决方案 2:
Python 后视断言需要固定宽度,但您可以尝试这样做:
>>> s = '"It "does "not "make "sense", Well, "Does "it"'
>>> re.sub(r's*"(?!,|$)', '" "', s)
'"It" "does" "not" "make" "sense", Well, "Does" "it"'
解释:
# Start the match at the end of a "word"
s* # Match optional whitespace
" # Match a quote
(?!,|$) # unless it's followed by a comma or end of string
解决方案 3:
最简单的解决方案是:
import regex as re
regex 支持不同长度的后视模式。