我试图为JS编写一个或多或少复杂的regEx。它通过我所有的测试,除了两个,我不知道为什么。这是代码如何正确使用JS regEx中的“或”命令?
function telephoneCheck(str) {
regEx1 = /^[1]\s(\d{3}[-]){2}\d{4}|(\d{3}[-]){2}\d{4}$/;
regEx2 = /^\d{10}$/;
regEx3 = /^[1]\s(\d{3}\s){2}\d{4}|(\d{3}\s){2}\d{4}$/;
regEx4 = /^[1]\s[(]{1}\d{3}[)]{1}\d{3}[-]{1}\d{4}|[(]{1}\d{3}[)]{1}\d{3}[-]{1}\d{4}$/;
regEx5 = /^[1]\s[(]{1}\d{3}[)]{1}\s\d{3}[-]{1}\d{4}|[(]{1}\s\d{3}[)]{1}\d{3}[-]{1}\d{4}$/;
if (regEx1.test(str) || regEx2.test(str) || regEx3.test(str) || regEx4.test(str) || regEx5.test(str)) {
return true;
}
else {
return false;
}
}
,而这些都是两个测试它不正确地传递(两者都应该回来为false
但我得到true
代替):telephoneCheck("2(757)622-7382")
和telephoneCheck("(555-555-5555")
。 我的问题是如何正确使用|
(或)运算符(我认为这会使我的代码更好看)以及如何描述regEx中的表达式以匹配特定字符(例如,开始处的“1”的数量)?我做了[1]{1}
或[1]$
,但它似乎没有工作。 感谢您的任何提示和建议!
太多问题:关注一个。 – trincot
不需要'{1}'。 – trincot