如何检索字符串中每个可能的数字对的匹配项?

时间:2019-07-02 15:20:03

标签: javascript regex match

我需要找到一个正则表达式,该正则表达式检索字符串中每对可能的数字对。

我尝试过使用/\d{2}/g/[0-9][0-9]/g并在匹配一次字符后将其烧掉。

输入:"1234567890"

带有正则表达式的输出:["12", "34", "56", "78", "90"]

必需的输出:["12", "23", "34", "45", "56", "67", "78", "89", "90"]

2 个答案:

答案 0 :(得分:0)

喜欢吗?

const re = /\d{2}/g
let str = "1234567890"
let arr = str.match(re)
str = str.slice(1)
arr = arr.concat(str.match(re))
console.log(arr.sort((a, b) => a - b))

答案 1 :(得分:0)

我不认为有一种方法可以返回字符并且不使用match来使用它。但是,您可以将replacematch链接起来以达到预期的结果。

let input = '1234567890';
let output = input.replace(/\d(?=\d)/g, (m, i) => m + input[i + 1]).match(/\d\d/g);
// ["12", "23", "34", "45", "56", "67", "78", "89", "90"]