admin管理员组文章数量:1401247
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
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
Share Improve this question asked Oct 13, 2016 at 17:08 DreamsDreams 8,51611 gold badges50 silver badges73 bronze badges 1- Are you trying to match a phone number? (seems so, given that character set) You may want to see stackoverflow./questions/16699007/… – Stephen P Commented Oct 13, 2016 at 17:55
5 Answers
Reset to default 7What 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')
Your current regex just checks that any one character in the string matches the character class. Add anchors and a quantifier: /^[0-9\-\(\)]+$/
^
- "Beginning of input" anchor$
- "End of input" anchor+
- Require one or more of the preceding thing
Mind you, "()"
will match that regex. :-)
You need to repeat it with either *
or +
. You also need to anchor it with ^
and $
to contain the whole string.
console.log(/^[0-9\-\(\)]+$/.test('(12321)213213d'));
console.log(/^[0-9\-\(\)]+$/.test('(12321)213213'));
I believe adding input beginning/end characters will fix this. Like
^[0-9\-(\)]$/.exec('(12321)213213d')
https://developer.mozilla/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
/^[\d\(\)\-]+$/.test('(12321)213213d')
^ start, $ end, \d for digit and ()-,
I think you are looking for telephone number matcher, if your answer is yes then this is not right regex for it.
for telephone matcher visit this link
本文标签:
版权声明:本文标题:javascript - How to write a regex only allow numbers and "(", ")", "-" - S 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744215603a2595625.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论