1

I'm looking for strings where the two first digits are present (in any order) in the digits that follow the space character.First I tried

(\d)(\d)\s\d*(\1|\2)\d*[\1\2&&[^\3]][\d]*

but it seems that I can't use brackets with backreferences.I tried using the lookahead feature instead with

(\d)(\d)\s\d*(\1|\2)\d*(?!\3(\1|\2))\d*

but I isn't right.The idea was "look for two digits, followed by a space, followed by zero or more digits, followed by either of the captured digits, followed by zero or more digits, followed by one of the captured digits which ISN'T the one I got before, followed by zero or more digits".21 20329 is a match.Why?How do I look for the strings I need?

1 Answer 1

1

This is simpler.

^(\d)(\d) (?=.*?\1)(?=.*?\2)\d+

See demo

  1. The first lookahead ensures that the digit captured by Group 1 is present somewhere later in the string.
  2. The second lookahead ensures that the digit captured by Group 2 is present somewhere later in the string.
  3. If these conditions are met, the \d+ eats up all the digits after the space.
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, that's useful.That website is really helpful too.I wish I could upvote your answer but I have no reputation, sorry.
@user3648292: but you can accept this answer (and you'll get some points for that as well). Please read About SO, as your status suggests you have not done this yet.
hey, I looked at it again and got confused.It looks like it'll only match when \1 comes before \2, is that right?If so, that will be wrong in some cases, the order shouldn't matter at all
@user3648292 Thanks for your feedback, glad it works. No, the answer doesn't matter at all. See [demo](user3648292) That's because when the engines evaluate a lookahead, it does so planted at a certain position in the string. The position after the lookahead hasn't changed, so the two lookaheads could be in any order. See Mastering Lookahead and Lookbehind

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.