【问题标题】:Difference of regex anchors between .NET and javascript.NET 和 javascript 之间正则表达式锚点的区别
【发布时间】:2017-01-19 18:32:45
【问题描述】:

在我的前端,我在 javascript 中有一个正则表达式来检测电子邮件是否正确。

^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$

.NET 上的当前后端正则表达式验证是:

Regex.IsMatch(email, @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", RegexOptions.IgnoreCase);

想用 javascript 替换 .NET 正则表达式但我真的“迷失”了开始/结束字符。

在 .NET 正则表达式中,\A\Z 是否与我的 javascript 中的 ^$ 具有相同的实用程序?

我尝试如下替换我的 .NET 正则表达式,但即使在 Javascript 中它是正确的,它也无法检测到有效字符串:

Regex.IsMatch(email, @"\A(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))\Z", RegexOptions.IgnoreCase);

【问题讨论】:

  • 关于电子邮件验证没有重复:我的问题不是关于使用正确的正则表达式,而是关于 Javascript 和 C# 之间的开始/结束符号差异
  • 感谢 Jasen 提供参考。我试图保留 A 和 Z,但它没有正确验证字符串。
  • 好吧,现在你有第二个问题。您应该使用示例数据创建一个新帖子。
  • 给出的答案是错误的,为什么接受? Vladu 刚刚从 .NET 参考中粘贴了锚点的描述,在 JS 中,\A\Z 不受支持,$ 的行为不同。

标签: javascript .net regex


【解决方案1】:
^ -   The match must occur at the beginning of the string or line. 
$ -   The match must occur at the end of the string or line, or before \n at the end of the string or line.
\A -  The match must occur at the beginning of the string only (no multiline support).
\Z -  The match must occur at the end of the string, or before \n at the end of the string.

【讨论】:

  • 那么区别是支持还是不支持多行?
  • 我编辑了问题:我试图保留 A 和 Z 锚点,但它没有像在 javascript 中那样验证字符串
猜你喜欢
  • 1970-01-01
  • 2016-11-18
  • 2012-02-22
  • 2023-04-07
  • 2012-06-01
  • 2013-09-18
  • 1970-01-01
  • 1970-01-01
  • 2013-12-17
相关资源
最近更新 更多