3

It's quite hard to explain this using words, so perhaps I can just show what I'm wanting.

Currently I have the following code:

  const regex = /(\d?\s\+?\s\d)|(\d?\s\-?\s\d)/g
  const match = '1 + 2 - 7'.match(regex)
  console.log(match)

This returns two matches:

[ "1 + 2", " - 7" ]

Now, what I want to know, is it possible to create a regex pattern that can match the integer 2 twice and make it part of two results?

Desired output:

[ "1 + 2", "2 - 7" ]
Joss Classey
  • 1,054
  • 1
  • 7
  • 22

1 Answers1

6

You could use a capturing group in a positive lookahead and use a character class [+-] to match either + or -

(?=(\d+ [+-] \d+))

Pattern parts

  • (?= Positive lookahead, assert what is directly on the right is
    • ( Capture group 1
      • \d+ [+-] \d+ Match 1+ digits, space, either + or -, space and 1+ digits
    • ) Close group
  • ) Close lookahead

Regex demo

Note that \s will also match a newline.

const regex = /(?=(\d+ [+-] \d+))/g;
const str = `1 + 2 - 7`;
let m;

while ((m = regex.exec(str)) !== null) {
  // This is necessary to avoid infinite loops with zero-width matches
  if (m.index === regex.lastIndex) {
    regex.lastIndex++;
  }

  console.log(m[1]);
}
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
  • 1
    @JossClassey If you don't use a while loop, you will only get the first result. [This page](https://stackoverflow.com/questions/9214754/what-is-the-difference-between-regexp-s-exec-function-and-string-s-match-fun) might be helpful about [exec](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec) – The fourth bird Aug 26 '19 at 15:47
  • 1
    Thank you for the clarification and for the great answer :) – Joss Classey Aug 26 '19 at 15:48