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

Match a repeating digit (the same one) exactly two times in Javascript with RegEx - Stack Overflow

programmeradmin0浏览0评论

I'm currently trying to match a repeating digit and so far I've got this:

pattern = /(\d){2}/

But when I test this pattern with a number of any length >= 2 it will return true. What I want to find is the following: When I test the number 12344 it should return true and if the number is 12345 it should return false. But having a number of 12444 should also return false. I want to find the same digit repeated exactly twice.

EDIT: Thanks to anybody proposing a solution!

I'm currently trying to match a repeating digit and so far I've got this:

pattern = /(\d){2}/

But when I test this pattern with a number of any length >= 2 it will return true. What I want to find is the following: When I test the number 12344 it should return true and if the number is 12345 it should return false. But having a number of 12444 should also return false. I want to find the same digit repeated exactly twice.

EDIT: Thanks to anybody proposing a solution!

Share Improve this question edited Mar 6, 2017 at 10:08 kidman01 asked Mar 6, 2017 at 9:46 kidman01kidman01 9555 gold badges18 silver badges33 bronze badges 6
  • You have to think about word boundaries, and maybe even making sure that the characters before and after the selection are not digits – evolutionxbox Commented Mar 6, 2017 at 9:50
  • 1 For numbers like 11222 should the output be true or false? – Aran-Fey Commented Mar 6, 2017 at 9:59
  • @evolutionxbox, not quite since I will always test a number, not a string with words and/or numbers mixed – kidman01 Commented Mar 6, 2017 at 10:07
  • @Rawing ha... tricky. I didn't even think of that. In this case it should still return true though. The answer I marked as the solution does exactly that. – kidman01 Commented Mar 6, 2017 at 10:08
  • @kidman01 you also only count consecutively repeated digits, right? So 1213 wouldn't be a match though 1 is repeated? – Sebastian Proske Commented Mar 6, 2017 at 10:13
 |  Show 1 more ment

2 Answers 2

Reset to default 8

For this kind of task you have to use lookarounds and backreferences:

(?:^|(.)(?!\1))(\d)\2(?!\2)

Explanation:

(?:         // match either...
    ^       // start of the string
|           // or...
    (.)     // any character
    (?!\1)  // not followed by the exact same character
)
(\d)        // then, match and capture a digit
\2          // and the same digit a 2nd time
(?!\2)      // and assert the digit doesn't show up a 3rd time
/(00|11|22|33|44|55|66|77|88|99)/
发布评论

评论列表(0)

  1. 暂无评论