Regex: Match 2 starts with the last sign from match 1

Viewed 42

is it possible to write a regex where the last sign from match 1 is the start sign of match 2? I like to match all numbers between brackets and separated by a pipe. The situation is also complicated by the fact that, the match can only have one group deep.

This is my string: Text (1234|5678|901) Text (222) Text (333|444)

And I like to get:

  • 1234
  • 5678
  • 901
  • 222
  • 333
  • 444

But the regex schouldn't match:

  • Text (123 Text
  • Text |123) Text
  • Text |123 Text

I only found this regex [(|]{1}(\d+) with the problem, he also matched something like this Text (123 Text.

I have an example on regex101: https://regex101.com/r/taOU8o/1

2 Answers

As you have selected Javascript in the regex demo link, if a quantifier in the lookbehind is supported you might use:

(?<=\((?:\d+\|)*)\d+(?=(?:\|\d+)*\))

The pattern matches:

  • (?<= Positive lookbehind, assert what is to the left is
    • \( Match (
    • (?:\d+\|)* Match optional repetitions of 1+ digits and |
  • ) Close lookbehind
  • \d+ Match 1+ digits
  • (?= Positive lookahead, assert what is to the right is
    • (?:\|\d+)* Match optional repetitions of | and 1+ digits
    • \) Match )
  • ) Close lookahead

Regex demo

const regex = /(?<=\((?:\d+\|)*)\d+(?=(?:\|\d+)*\))/g;
const str = `Text (1234|5678|901) Text (222) Text (333|444)
Text (123 Text
Text |123) Text
Text |123 Text
`;

console.log(str.match(regex));

If you need a capture group, wrap the digits in parenthesis

(?<=\((?:\d+\|)*)(\d+)(?=(?:\|\d+)*\))

Regex demo

You can use

\(\d+(?:\|\d+)*\)

See the regex demo. Details:

  • \( - a ( char -\d+ - one or more digits
  • (?:\|\d+)* - zero or more reptitions of a | and then one or more digits
  • \) - a ) char.
Related