我对Python中的lookaround有一个问题:
>>> spacereplace = re.compile(b'(?<!\band)(?<!\bor)\s(?!or\b)(?!and\b)', re.I)
>>> q = "a b (c or d)"
>>> q = spacereplace.sub(" and ", q)
>>> q
# What is meant to happen:
'a and b and (c or d)'
# What instead happens
'a and b and (c and or and d)'
正则表达式应该匹配任何不在单词“and”或“or”旁边的空格,但这似乎不起作用。你知道吗
有人能帮我吗?你知道吗
编辑:作为对注释者的回应,我将regex分解为多行。你知道吗
(?<!\band) # Looks behind the \s, matching if there isn't a word break, followed by "and", there.
(?<!\bor) # Looks behind the \s, matching if there isn't a word break, followed by "or", there.
\s # Matches a single whitespace character.
(?!or\b) # Looks after the \s, matching if there isn't the word "or", followed by a word break there.
(?!and\b) # Looks after the \s, matching if there isn't the word "and", followed by a word break there.
您可能将原始字符串修饰符
r
与b
混淆了。你知道吗有时,如果regexp不起作用,那么使用
re.DEBUG
标志DEBUG
可能会有所帮助。在这种情况下,您可能会注意到,没有检测到单词boundary\b
,这可能会提示您在何处搜索错误:相关问题 更多 >
编程相关推荐