Python 中的正则表达式 [^.]
import re
str="Everyone loves Stack Overflow"
print(re.findall("[ESO][^.]",str))
我不明白为什么 [^.]
会做任何事情。我认为它只匹配不是字符的字符 - 换句话说:什么都没有!但输出如下:
['Ev', 'St', 'Ov']
有人可以解释一下吗?在谷歌上搜索像 [^.]
这样的东西是不可能的,关于正则表达式的 pythondocs 也没有帮助。
import re
str="Everyone loves Stack Overflow"
print(re.findall("[ESO][^.]",str))
I don't understand why [^.]
does anything. I thought it only matches characters that are not characters - in other words: nothing! But the output is the following:
['Ev', 'St', 'Ov']
Can someone shed some light on this? It's impossible to search for something like [^.]
on google, and pythondocs about regular expressions didn't help either.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
大多数正则表达式特殊字符会失去其在字符类(方括号)中的特殊含义,因此,虽然
.
匹配任何字符,但[.]
匹配文字.
和[^.]
匹配.
以外的任何字符。有时您会看到人们将像.
这样的字符放在方括号中,只是为了确保按字面意思处理它,而不必担心正则表达式库中的任何极端情况。Most of the regular expression special characters lose their special meaning within a character class (square brackets), so while
.
matches any character,[.]
matches a literal.
and[^.]
matches any character other than.
. You will sometimes see people wrap a character like.
in square brackets just to make sure it's treated literally without having to worry about any corner cases in a regular expression library.字符类
[]
有自己的小语言。具体来说,字符类中的点.
与实际的.
匹配(并且不是通配符)。Character classes
[]
have their own little language. Specifically, the dot.
inside a character class matches the actual.
(and is not a wildcard).大多数字符在字符组内时会失去其特殊含义。
因此
.
匹配任何字符,但[.]
仅匹配点。因此[^.]
匹配除点之外的所有内容。Most characters lose their special meaning when they are inside a character group.
So
.
matches any character, but[.]
matches only dot. Thus[^.]
matches everything that is not dot.