javascript:编译器将 // 解释为正则表达式中的注释时出现一些问题
我有这个用于验证电话号码的正则表达式,
^(\+?|(\(\+?[0-9]{1,3}\))|)([ 0-9.//-]|\([ 0-9.//-]+\))+((x|X|((e|E)(x|X)(t|T)))([ 0-9.//-]|\([ 0-9.//-]+\)))?$
我从我的 C#/vb 库中挖出了它,现在我想将它翻译成 JavaScript。但它有语法错误(我怀疑这是由于//字符造成的)。我的尝试:
$IsPhone = function (input) {
var regex = new window.RegExp("^$|^(\+?|(\(\+?[0-9]{1,3}\))|)([ 0-9.//-]|\([ 0-9.//-]+\))+((x|X|((e|E)(x|X)(t|T)))([ 0-9.//-]|\([ 0-9.//-]+\)))?$", "");
return regex.test(input.trim());
};
alert($IsPhone("asd"));
I've got this regular expression for validating phone numbers
^(\+?|(\(\+?[0-9]{1,3}\))|)([ 0-9.//-]|\([ 0-9.//-]+\))+((x|X|((e|E)(x|X)(t|T)))([ 0-9.//-]|\([ 0-9.//-]+\)))?$
I dugged it out from my C#/vb library and now i want to translate it into javascript. But it has syntax error (i suspect it is something due to the // characters). my attempt:
$IsPhone = function (input) {
var regex = new window.RegExp("^$|^(\+?|(\(\+?[0-9]{1,3}\))|)([ 0-9.//-]|\([ 0-9.//-]+\))+((x|X|((e|E)(x|X)(t|T)))([ 0-9.//-]|\([ 0-9.//-]+\)))?$", "");
return regex.test(input.trim());
};
alert($IsPhone("asd"));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你的问题与评论无关。您只是混合了创建 RegExp 对象的两种不同方法。
当您在 JavaScript 代码中创建 RegExp 对象时,您可以将其编写为传递给 RegExp 构造函数的字符串文字,也可以编写为正则表达式文字。由于字符串文字支持反斜杠转义序列,例如
\n
和\"
,因此字符串中的任何实际反斜杠也必须进行转义。因此,每当您需要转义正则表达式元字符如(
或+
,您必须使用两个反斜杠,如下所示:正斜杠对于正则表达式没有特殊含义或字符串。您必须转义正斜杠的唯一原因是它们用作正则表达式文字的分隔符,您可以使用反斜杠来转义正斜杠,就像使用
\(
或\+
,或反斜杠本身:\\
。这是正则表达式的正则表达式文字版本:Your problem has nothing to do with comments. You're just mixing up the two different ways of creating RegExp objects.
When you create a RegExp object in JavaScript code, you either write it as a string literal which you pass to a RegExp constructor, or as a regex literal. Because string literals support backslash-escape sequences like
\n
and\"
, any actual backslash in the string has to be escaped, too. So, whenever you need to escape a regex metacharacter like(
or+
, you have to use two backslashes, like so:The forward-slash has no special meaning, either to regexes or strings. The only reason you ever have to escape forward-slashes is because they're used as the delimiter for regex literals. You use backslashes to escape the forward-slashes just like you do with regex metacharacters like
\(
or\+
, or the backslash itself:\\
. Here's the regex-literal version of your regex:来自 将正则表达式从 .NET 转换为 javascript 时出错
from Errors translating regex from .NET to javascript