regular expression include existing matches in search

Viewed 36

I am trying to capture parts of an equation using a regular expression.

Equation: 1×2÷3×4

Regular expression: \d+(×|÷)\d+

I expect this to result in:

1×2

2÷3

3×4

But it only returns:

1×2

3×4

I assume this has something to do with the structure, but I'm not even sure where to start or what to google to find the answer.

2 Answers

If your regex matches something then it will continue after that match so that's why you are getting only two matches. You can use (?=abc) positive lookahead to just see that if there is ([×÷]) and capture it and (\d) after the match.

You can use

/\d(?=([×÷])(\d))/g

enter image description here

The below code is specifically in Javascript

const regex = /\d(?=([×÷])(\d))/g;
const str = "1×2÷3×4";

const results = [...str.matchAll(regex)].map((arr) => {
  return `${arr[0]}${arr[1]}${arr[2]}`;
});

console.log(results);

Each part of the string will only be matched to the pattern one time - once the substring "1x2" has matched the regular expression, the '2' won't be re-used in subsequent matches. Consider the string "×2÷3×4" (i.e. drop the first '1') - in this case the first (and only) match is "2÷3".

Related