最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript regex - check number of numeric-only matches - Stack Overflow

programmeradmin4浏览0评论

I have this regex thanks to another wonderful StackOverflow user

/(?:-\d+)*/g

I want it to match things like

133-134-454-58819860
12-13-876-1234346

each block (numbers between -'s) could be any length but it will defiantly only be numbers and there will only 4 blocks.

But currently it's matching things like -2008

I'm really bad at regex and I'm struggling, please help. I'm in JavaScript if that's helpful.

I have this regex thanks to another wonderful StackOverflow user

/(?:-\d+)*/g

I want it to match things like

133-134-454-58819860
12-13-876-1234346

each block (numbers between -'s) could be any length but it will defiantly only be numbers and there will only 4 blocks.

But currently it's matching things like -2008

I'm really bad at regex and I'm struggling, please help. I'm in JavaScript if that's helpful.

Share Improve this question edited May 23, 2017 at 12:04 CommunityBot 11 silver badge asked Sep 13, 2009 at 8:35 Ben ShelockBen Shelock 21k26 gold badges97 silver badges126 bronze badges 2
  • 1 if you want to get better with RegEx's, a free tool like Expresso or the Regulator is very helpful... – Mitch Wheat Commented Sep 13, 2009 at 8:37
  • Thanks Mitch. I've been using RegExr but I'll check that one out :) – Ben Shelock Commented Sep 13, 2009 at 8:40
Add a ment  | 

4 Answers 4

Reset to default 6
/(?:-\d+)*/g

breaks down into:

/    about to begin a regex

(    the following is a group

?:   but don't bother storing what this group finds as its own result

-    it must have a dash

\d   followed by digit(s)...

+    at least one digit, perhaps more

)    Im done with the group

*    But get me as many groups like that as you could

/    done with the regex

So it will find all groups like this -0000 but not like this -000-000

While writing this, other faster users published their own regexs. But Im still posting so you follow the logic.

Try this

/(?:\d+-){3}\d+/

If you want to match exactly four hyphen-separated numeric strings, you would want this:

/^\d+-\d+-\d+-\d+$/

The ^ and $ are anchors to constrain the match to the very beginning and very end of the string. You'll want to remove those if you are looking in a string with other text (e.g. "blah blah 12-12-12-12 blah blah").

As far as checking the number of matches, the following should work:

alert(
  "133-134-454-58819860".match(/^(\d+-){3}\d+$/g).join("\n")
 );

The match function of JavaScript strings takes a regular expression object as a parameter. It returns an array of matches, in the order in which they were found within the string.

发布评论

评论列表(0)

  1. 暂无评论