0

convert a regular expression to all possible cases

For Example:

1.9856[1-4] then it should return values like 98561,98562,98563,98564

2.98[4-5]65 then it should return values 98465,98565

2 Answers2

0

You can use the regex /\[(\d)-(\d)\]/ and match to get the start and end of the range. Then use a for loop to replace the match with numbers from start to end

function getCombinations(str) {
  const regex = /\[(\d)-(\d)\]/,
        [match, start, end] = str.match(regex),
        output = []

  for (let i = +start; i <= +end; i++)
    output.push(str.replace(match, i))
  
  return output
}

console.log(getCombinations('1.9856[1-4]'))
console.log(getCombinations('2.98[4-5]65'))

This works for only single range in the input string. For multiple ranges, you can use exec to get multiple matches and replace based on the index of the match

adiga
  • 34,372
  • 9
  • 61
  • 83
0

You can use Regex to match exact numbers or you can use \d to match any digits.

For your first example where 9856[1-4] then it should return values like 98561,98562,98563,98564, you can return all numbers in a string that begin with 9856 and ends with any number ranging from 1-4 like so:

let nums = "985612, 985622, 985633, 985644, 985655"

let regex = /9856[1-4]/g

let result = nums.match(regex)

console.log(result)

For the second example where 98[4-5]65 then it should return values 98465, 98565

let nums = "98465, 98565"

let regex = /98[4-5]{2}65/g

let result = nums.match(regex)

console.log(result)

F.young
  • 1
  • 1
  • 2