如何编写正则表达式只允许数字和“(”,“)”,“ - ”(How to write a regex only allow numbers and “(”, “)”, “-”)
下面是我的正则表达式,但它似乎无法正常工作
/[0-9\-\(\)]/.test(str)当我测试
/[0-9\-\(\)]/.test('(12321)213213d')它会返回true
Below is my regex but it seems not working
/[0-9\-\(\)]/.test(str)when I test
/[0-9\-\(\)]/.test('(12321)213213d')It will return true
最满意答案
你实际测试的是你的测试字符串中是否有这些字符。 您想检查它是否只包含那些字符。 要做到这一点,你需要说从开始^到完成$它只包含那些字符。
例如
/^[0-9()-]+$/.test('(12321)213213d')What you're actually testing is if any of those characters are in your test string. You want to check if it contains only those characters. To do that, you need to say from start ^ to finish $ it only contains those chars.
e.g.
/^[0-9()-]+$/.test('(12321)213213d')更多推荐
发布评论