使用正则表达式匹配不在字符 < > 内的单词

Match words that are not inside the characters < > using regular expressions

我正在尝试匹配不在 < > 中的单词。

这是<里面匹配单词的正则表达式 >:

text = " Hi <how> is <everything> going"
pattern_neg =  r'<([A-Za-z0-9_\./\-]*)>'
m = re.findall(pattern_neg, text)

# m is ['how', 'everything']

我希望结果是 ['Hi', 'is', 'going']

使用re.split

import re

text = " Hi <how> is <everything> going"
[s.strip() for s in re.split('\s*<.*?>\s*', text)]
>> ['Hi', 'is', 'going']

正则表达式方法:

>>> import re
>>> re.findall(r"\b(?<!<)\w+(?!>)\b", text)
['Hi', 'is', 'going']

其中 \b 是单词边界,(?<!<) 是负向后视,(?!>) 是负向前视,\w+ 将匹配一个或多个字母数字字符。

一种非正则表达式的朴素方法(按 space 拆分,检查每个单词是否不以 < 开头且不以 > 结尾):

>>> [word for word in text.split() if not word.startswith("<") and not word.endswith(">")]
['Hi', 'is', 'going']

为了同时处理 <hello how> are you 案例,我们需要一些不同的东西:

>>> text = " Hi <how> is <everything> going"
>>> re.findall(r"(?:^|\s)(?!<)([\w\s]+)(?!>)(?:\s|$)", text)
[' Hi', 'is', 'going']
>>> text = "<hello how> are you"
>>> re.findall(r"(?:^|\s)(?!<)([\w\s]+)(?!>)(?:\s|$)", text)
['are you']

请注意 are you 现在必须拆分才能获得单独的单词。