4

I need to find a regular expression that retrieves every possible pair of numbers that are together in a string.

I have tried with /\d{2}/g and /[0-9][0-9]/g and it burns the char after it matches it once.

input: "1234567890"

output with the regexp up there: ["12", "34", "56", "78", "90"]

required output: ["12", "23", "34", "45", "56", "67", "78", "89", "90"]

mplungjan
  • 169,008
  • 28
  • 173
  • 236
CRz
  • 51
  • 3

2 Answers2

0

Like this?

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))
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

I do not think there is a way to return a character and not consuming it using match. However, you could chain a replace and a match to achieve the expected result.

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"]
Bali Balo
  • 3,338
  • 1
  • 18
  • 35