我对 Python 中的外观有疑问:
>>> 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”旁边的空格,但这似乎不起作用。
谁能帮我这个?
编辑:作为对评论者的回应,我将正则表达式分解为多行。
(?<!\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.