admin管理员组文章数量:1391774
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 betrue
orfalse
? – 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 though1
is repeated? – Sebastian Proske Commented Mar 6, 2017 at 10:13
2 Answers
Reset to default 8For 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)/
本文标签: Match a repeating digit (the same one) exactly two times in Javascript with RegExStack Overflow
版权声明:本文标题:Match a repeating digit (the same one) exactly two times in Javascript with RegEx - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744765651a2624023.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论