javascript - 正则表达式中连字符的这种用法有效吗?

标签 javascript regex email

注意。我只想想知道它是否是正则表达式定义中未转义连字符的有效应用。这不是关于匹配电子邮件、连字符或反斜杠的含义、量词或其他任何内容的问题。另外,请注意,链接的答案并没有真正讨论转义/未转义连字符之间的有效性问题。

通常我会声明用于匹配电子邮件地址的正则表达式,如下所示。

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>');

显然,它是有效的,因为连字符是括号中的最后一个字符。我的问题是这只是一个巧合还是一个有效的语法?我一生都在错误地调整吗?

最佳答案

字符类中的连字符用于范围。但是,当放在字符类的开头或结尾时,无需转义。

请注意,在某些浏览器中,字符类中任何位置的连字符仍被视为范围元字符,因此最佳实践是始终对其进行转义。

引用自regular-expressions.info

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 an x or a hyphen. [^-x] and [^x-] match any character that is not an x 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/

相关文章:

javascript - 如何为动态聊天室配置 Autobahn(crossbar.io)?

java - 帮助使用正则表达式解析并获取 html 中 <p> 标记的内容

Python:在多个 CSS 选择器的复杂列表上使用正则表达式来提取它们的 # 和 .标签

email - 除了 Hotmail 之外,多部分电子邮件在任何地方都可以使用

java - 电子邮件 mime 解析

email - 骡子 ESB : how to filter emails based on subject or sender?

javascript - 输入数值以追加div

javascript - 子网格未填充在免费的 jqGrid 中

python - 使用 python 分割行并添加分隔符到文本文件

javascript - eventListener 按键对于 &lt;input&gt; 无法正确工作