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
Add a ment  | 

5 Answers 5

Reset to default 7

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')

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

本文标签: