我一直在尝试弄清楚如何包含某些词组并排除其他词组。例如我有这个字符串
string1="HI:MYDLKJL:ajkld? :JKLJBLKJD:DKJL? app?"
我想找到 HI:MYDLKJL:ajkld? 和 app? 但不是 :JKLJBLKJD:DKJL? 因为它的开头是:我已经制作了这段代码,但它仍然包含 :JKLJBLKJD:DKJL?只是忽略前面的 :
match3=re.findall("[A-Za-z]{1,15}[:]{0,1}[A-Za-z]{0,15}[:]{0,1}[A-Za-z]{0,15}[:]{0,1}[A-Za-z]{0,15}[\?]{1}",string1)
请您参考如下方法:
实际的模式很容易指定。但是,您还需要指定一个回顾来适本地处理第二个术语。
>>> re.findall(r'(?:(?<=\s)|(?<=^))[^:]\S+\?', string1)
['HI:MYDLKJL:ajkld?', 'app?']
正则表达式的意思是“任何不以冒号开头但以问号结尾的表达式”。
(?: # lookbehind
(?<=\s) # space
| # OR
(?<=^) # start-of-line metachar
)
[^:] # anything that is not a colon
\S+ # one or more characters that are not a space
\? # literal question mark
简单的单词边界不起作用,因为 \b 也将匹配 : 和 JKLJBLKJD 之间的边界...没有布埃诺,因此回顾。
