如何在 Python 中使用正则表达式排除特定字符串? [英] How to exclude specific string using regex in Python?
问题描述
我想匹配如下字符串:
45 meters?
45, meters?
45?
45 ?
但不是像这样的字符串:
but not strings like:
45 meters you?
45 you ?
45, and you?
在这两种情况下,问号都必须在末尾.所以,基本上我想排除所有包含你"这个词的字符串.
In both cases the question mark must be at the end. So, essentially I want to exclude all those strings containing the word "you".
我尝试了以下正则表达式:
I've tried the following regex:
'\d+.*(?!you)\?$'
但它匹配第二种情况(可能是因为.*
)
but it matches the second case (probably because of .*
)
推荐答案
你可以试试这个正则表达式来匹配所有没有字符串 you
和 的行?
最后,
You could try this regex to match all the lines which doesn't have the string you
with ?
at the last,
^(?!.*you).*\?$
说明:
在这个正则表达式中使用了负前瞻.它实际上意味着什么,它检查包含字符串 you
的行.它匹配除包含字符串 you
的行之外的所有行.
A negative lookahead is used in this regex. What it does actually means, it checks for the lines which contains a string you
. It matches all the lines except the line containing the string you
.
这篇关于如何在 Python 中使用正则表达式排除特定字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!