javascript - 使用 RegEx 在 Javascript 中匹配重复数字(相同的数字)两次

标签 javascript regex

我目前正在尝试匹配一个重复的数字,到目前为止我已经得到了这个:

pattern = /(\d){2}/

但是当我使用任意长度 >= 2 的数字测试此模式时,它将返回 true。我想找到的是以下内容: 当我测试数字 12344 时,它应该返回 true,如果数字是 12345,它应该返回 false。但是拥有 12444 的数字也应该返回 false。我想找到重复两次的相同数字。

编辑:感谢任何提出解决方案的人!

最佳答案

对于这种任务,您必须使用环视和反向引用:

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

解释:

(?:         // 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

关于javascript - 使用 RegEx 在 Javascript 中匹配重复数字(相同的数字)两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42622292/

相关文章:

java - 除特定情况外如何匹配单个字符

javascript - 如何使用Javascript显示选择选项的值

javascript - 正则表达式获取 HTML 中最后一个 </body> 标签

javascript - Vue.js JSON 多次分组数组

javascript - 更改有效的现有脚本

c# - 仅替换字符串开头的字符

java - 优化 Regex 以提取两个标签之间的内容(或 How to select content between two tags with Jsoup selector API?)

java - yyyyMMdd 的正则表达式日期验证

javascript - 在 Meteor 中为 CloudMQTT 配置 mqttConnect 选项

javascript - 如何避免在输入文本表单中输入重复的数字?