注意。我只想想知道它是否是正则表达式定义中未转义连字符的有效应用。这不是关于匹配电子邮件、连字符或反斜杠的含义、量词或其他任何内容的问题。另外,请注意,链接的答案并没有真正讨论转义/未转义连字符之间的有效性问题。
通常我会声明用于匹配电子邮件地址的正则表达式,如下所示。
var emailPattern = /^[a-z.\-_]+@[a-z]+[.]{1}[a-z]{2,3}$/;
emailPattern.test('<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3b4848155a645a167b5a484815585456" rel="noreferrer noopener nofollow">[email protected]</a>');
现在,我的一位同事错误地忘记了转义字符,并且 **仍然* 使它起作用,这让我感到惊讶,因为连字符的间隔含义。看起来像这样。
var weirdPattern = /^[a-z._-]+@[a-z]+[.]{1}[a-z]{2,3}$/;
weirdPattern.test('<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ddaeaef3bc82bcf09dbcaeaef3beb2b0" rel="noreferrer noopener nofollow">[email protected]</a>');
显然,它是有效的,因为连字符是括号中的最后一个字符。我的问题是这只是一个巧合还是一个有效的语法?我一生都在错误地调整吗?
最佳答案
字符类中的连字符用于范围。但是,当放在字符类的开头或结尾时,无需转义。
请注意,在某些浏览器中,字符类中任何位置的连字符仍被视为范围元字符,因此最佳实践是始终对其进行转义。
The hyphen can be included right after the opening bracket, or right before the closing bracket, or right after the negating caret. Both
[-x]
and[x-]
match anx
or a hyphen.[^-x]
and[^x-]
match any character that is not anx
or a hyphen. Hyphens at other positions in character classes where they can't form a range may be interpreted as literals or as errors. Regex flavors are quite inconsistent about this.
关于javascript - 正则表达式中连字符的这种用法有效吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36939790/