Regex match repeated digits without sorting

Viewed 60

In a string like this

16,17,22,22,22,22,20,16

I'm trying to match the repeated digits without sorting.

I tried (\d+)\1+ and many variations but it doesn't work.

Thank you in advance for your help.

1 Answers

You can use

console.log("16,17,22,22,22,22,20,16".match(
     /\b(\d+)\b(?:(?<=\b\1\b.*\b\1\b)|(?=.*\b\1\b))/g
))

See the regex demo

Details

  • \b(\d+)\b - one or more digits captured into Group 1 that are enclosed with word boundaries
  • (?:(?<=\b\1\b.*\b\1\b)|(?=.*\b\1\b)) - a non-capturing group matching either of the two patterns:
    • (?<=\b\1\b.*\b\1\b) - a location immediately preceded with the same value as captured in Group 1 (as a whole word), then any zero or more chars other than line break chars and again such value as in Group 1 (this second one just matches what \b(\d+)\b matched since the lookbehind is located after the Group 1)
    • | - or
    • (?=.*\b\1\b) - a location immediately followed with any zero or more chars other than line break chars as many as possible and then Group 1 value as a whole word.
Related