[英]Invalid Group with Regex Expression in Javascript
I've looked around for solutions to my problem but I cannot see what part of my regex expression is invalid (javascript says that I have an invalid group). 我四处寻找我的问题的解决方案,但我看不出我的正则表达式的哪一部分无效(javascript说我有一个无效的组)。 I imagine that I am using something which isn't support by javascript's regex engine?
我想我正在使用javascript的正则表达式引擎不支持的东西?
I'm trying to validate US phone numbers like the following: 我正在尝试验证以下美国电话号码:
555-555-5555
(555)555-5555
(555) 555-5555
555 555 5555
5555555555
1 555 555 5555
And my expression for validations is: 我的验证表达是:
1?[\s-]?\(?(\d{3})\)?[\s-]?(\d{3})[\s-]?(\d{4})
Any tips? 有小费吗?
/1?[\\s-]?\\(?(\\d{3})\\)?[\\s-]?(\\d{3})[\\s-]?(\\d{4})/
works fine in JavaScript. /1?[\\s-]?\\(?(\\d{3})\\)?[\\s-]?(\\d{3})[\\s-]?(\\d{4})/
作品很好的JavaScript。
However, my crystal ball says you're using a string that you're passing to the RegExp
constructor: 但是,我的水晶球说你正在使用一个你传递给
RegExp
构造函数的字符串:
new RegExp("1?[\s-]?\(?(\d{3})\)?[\s-]?(\d{3})[\s-]?(\d{4})")
This is wrong because backslashes have a special meaning in strings, so 这是错误的,因为反斜杠在字符串中有特殊含义,所以
"1?[\s-]?\(?(\d{3})\)?[\s-]?(\d{3})[\s-]?(\d{4})"
is equivalent to 相当于
"1?[s-]?(?(d{3}))?[s-]?(d{3})[s-]?(d{4})"
(because "\\("
is "("
). That would complain about an invalid group at (?(
. (因为
"\\("
是"("
)。那会抱怨(?(
。
Solution: Either use a regex literal ( /.../
) or double your backslashes in the string. 解决方案:使用正则表达式文字(
/.../
)或在字符串中加倍反斜杠。
你试过下面的吗?
^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.