带有可选空格的正则表达式否定环视

Regex negative lookaround with optional whitespace

我正在尝试查找数字,但某些单词没有成功。我在 Python3 中使用正则表达式来执行此操作。我的猜测是必须使用负面环视,但由于可选的空格,我正在苦苦挣扎。请参阅以下示例:

'200 word1 some 50 foo and 5foo 30word2'

请注意,实际上 word1 和 word2 可以替换为很多不同的词,这使得搜索这些词的肯定匹配变得更加困难。因此,排除 foo 之后的数字会更容易。预期结果是:

[200, 30]

我的尝试:

s = '200 foo some 50 bar and 5bar 30foo
pattern = r"[0-9]+\s?(?!foo)"
re.findall(pattern, s)

结果

['200', '50 ', '5', '3']

您应该使用模式 \b[0-9]+(?!\s*foo\b)(?=\D),它表示查找所有后面没有可选空格和单词 foo.

的数字
s = '200 word1 some 50 foo and 5foo 30word2'
matches = re.findall(r'\b[0-9]+(?!\s*foo\b)(?=\D)', s)
print(matches)

这会打印:

['200', '30']

您可以使用

import re
s = '200 word1 some 50 foo and 5foo 30word2'
pattern = r"\b[0-9]+(?!\s*foo|[0-9])"
print(re.findall(pattern, s))
# => ['200', '30']

参见Python demo and the regex graph

详情

  • \b - 单词边界
  • [0-9]+ - 仅 1+ 个 ASCII 数字
  • (?!\s*foo|[0-9]) - 没有立即跟随
    • \s*foo - 0+ 个空格和 foo 字符串
    • | - 或
    • [0-9] - ASCII 数字。