3

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.

2
  • What do you mean by "without sorting"? And what result are you expecting? Commented Oct 27, 2020 at 12:06
  • I mean i don't want to split and sort and join again. The result I expect would be an array of the digits that repeat in the string [16, 22, 22, 22, 22, 16] Commented Oct 27, 2020 at 12:10

1 Answer 1

1

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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.