Home: Perl Programming Help: Regular Expressions:
Matching first instance before AND after something



JojoZiggy
New User

Sep 3, 2010, 7:35 AM


Views: 6666
Matching first instance before AND after something

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.


shawnhcorey
Enthusiast


Sep 3, 2010, 8:46 AM


Views: 6663
Re: [JojoZiggy] Matching first instance before AND after something

Try:

Code
$string =~ /.*(MARY.+?HELLO.+?BILL)/;


__END__

I love Perl; it's the only language where you can bless your thingy.

Perl documentation is available at perldoc.perl.org. The list of standard modules and pragmatics is available in perlmodlib.

Get Markup Help. Please note the markup tag of "code".


JojoZiggy
New User

Sep 3, 2010, 8:52 AM


Views: 6662
Re: [shawnhcorey] Matching first instance before AND after something

ACK of course!
Thanks!!