1

I have a string that looks like this

aa bcdef123efg hh aa lklmasd456 hh (whitespace and bolding is used for illustration)

If I have 456, I want to find where 456 is and grab everything in between aa and hh.

This is the regex that I was able to come up with so far (?=aa)(.*)456(.*)(?=hh)

However, that doesn't stop at the first occurance of aa it encounters (backwards from the 456 match)

What would be the proper syntax for what I'm trying to achieve.

8
  • 1
    /aa(.*?456.*?)hh/? Commented Aug 26, 2014 at 18:16
  • so given your string, what is the expected match? Commented Aug 26, 2014 at 18:18
  • Are you just trying to extract the string between aa and hh? Is it always hhaa or are there characters between them? If not, what about exploding them into an array and using inarray() to find strings with '456'? Commented Aug 26, 2014 at 18:20
  • @MarcB aa(.*?456.*?)hh won't stop at first hh Commented Aug 26, 2014 at 18:22
  • @anubhava: the ungreedy .*? should allow for that. Commented Aug 26, 2014 at 18:23

1 Answer 1

1

You can use this lookaround based regex:

aa((?:(?!hh).)*?456(?:(?!hh).)*?)hh

RegEx Demo

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.