【问题标题】:Why is [^@] regular expression acting the way it does?为什么 [^@] 正则表达式的行为方式如此?
【发布时间】:2016-01-24 02:09:31
【问题描述】:

当我发现这个时,我正在寻找一个正则表达式来验证电子邮件:

[^@]+@[^@]+\.[^@]+

[^@] 表达式似乎不像文档所说的那样工作。

s = 'test'

match = re.match("[^@]", s)

print(match.group())

这例如打印字符串的第一个字符t。 如果我使用正则表达式[^],我会得到一个错误:unexpected end of regular expression。文档说:

特殊字符在集合中失去其特殊意义。

[] 是一个集合,^ 是一个特殊字符。

【问题讨论】:

  • 确保恰当地命名问题。 [^@] 表达式的工作原理完全与文档中的一样,并且没有其他情况;引发错误的是 [^] 表达式。

标签: python regex python-3.x


【解决方案1】:

“特殊字符在集合中失去其特殊含义”这一说法是正确的,因为插入符号有两个特殊含义;在正则表达式的逻辑开始处(它是锚点),以及字符类的开始处 (or 'character set' where it forms a 'complementing set of characters')。

报告的错误来自 [^] 构造,该构造无效,因为字符类未关闭:^ 影响下一个字符。

这种情况下的效果是]没有没有关闭字符类,整个正则表达式“没有结束”,导致正则表达式语法错误。


无论如何,关于[^] 的错误报告与[^@] 无关,[^@] 是一个可以匹配任何字符除了 @ 的字符类。这一点,再加上不正确的标题,可能解释了一些反对意见..

re.match("[^]",  "anything")  # => regex error, as explained above
re.match("[^]]", "z")         # => match; z is not ]
re.match("[^@]", "z")         # => match; z is not @
re.match("[^@]", "@")         # => no match

【讨论】:

    【解决方案2】:

    [^] 是一个特例。它的意思是“匹配一个不在括号中的字符”。查看the wiki page 了解更多详情。

    【讨论】:

      【解决方案3】:

      字符^是一个特殊字符。

      ^Test ... matches a string that starts with Test
         \^ ... matches the character ^
       [\^] ... matches the character ^
       [^^] ... matches a character that is not a ^
       [-^] ... matches a - or a ^
       [^-] ... matches a character that is not a -
      [\^-] ... matches a - or a ^
      

      【讨论】:

      • 这个问题更多的是关于为什么插入符号的行为方式,而不是表达式的含义。
      猜你喜欢
      • 2015-02-11
      • 2010-10-20
      • 2017-01-10
      • 2013-06-02
      • 1970-01-01
      • 2018-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多