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). I imagine that I am using something which isn't support by javascript's regex engine?
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.
However, my crystal ball says you're using a string that you're passing to the RegExp
constructor:
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}$
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.