为什么[^ @]正则表达式的行为方式如此?

时间:2016-01-24 02:09:32

标签: python regex python-3.x

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

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

[^@]表达似乎不像文档所说的那样有效。

s = 'test'

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

print(match.group())

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

  

特殊角色在内部失去了特殊意义。

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

3 个答案:

答案 0 :(得分:5)

声明"特殊字符在集合中失去了特殊含义"是真的,因为插入符有两个特殊含义;在正则表达式的逻辑起点(它是锚点),以及字符类(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 除外的任何字符匹配的字符类。这与错误关注的标题相结合,可能解释了一些downvotes ..

add_subdirectory

答案 1 :(得分:0)

[^]是一个特例。这意味着“匹配不在括号中的单个字符”。有关更多详细信息,请查看the wiki page

答案 2 :(得分:0)

角色^是一个特殊角色。

^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 ^