
JojoZiggy
New User
Sep 3, 2010, 7:35 AM
Post #1 of 3
(1665 views)
|
|
Matching first instance before AND after something
|
Can't Post
|
|
Hi, gurus. This problem seems really simple, but I can't figure out an easy way to do it. Sorry if it's a commonly asked question, I didn't see it in the first 5 pages of the FAQ or REGEX pages (but maybe I didn't know what to look for...). In this string, MARYMARYMARYJUNKHELLOJUNKBILLBILLBILL I want to match the first "MARY" before "HELLO" and the first "BILL" after "HELLO", and then pull out all the text in between. So what I want in the end is "MARYJUNKHELLOJUNKBILL" Here's the code I tried first: $string = "MARYMARYMARYJUNKHELLOJUNKBILLBILLBILL"; $string =~ /(MARY.+?HELLO.+?BILL)/; print "first try: " . $1 . "\n"; # returns MARYMARYMARYJUNKHELLOJUNKBILL Next, I tried this, thinking breaking out the two matches would help, but no luck: $string = "MARYMARYMARYJUNKHELLOJUNKBILLBILLBILL"; $string =~ /(HELLO.+?BILL)/; $stuff = $1; # returns HELLOJUNKBILL print "bill match: " . $stuff . "\n"; $string =~ /(MARY.+?$stuff)/; print "mary match: " . $1 . "\n"; # returns MARYMARYMARYMARYMARYJUNKHELLOJUNKBILL Thanks for your time.
|