Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I'm looking for an RE which will do something like this:

"hello there <here I am> today is sunny"

I want to grab everything between the characters < and > . It should return the string

"here i am"

thanks

  • Comment on Retrieving text between 2 strings/chars...

Replies are listed 'Best First'.
Re: Retrieving text between 2 strings/chars...
by dda (Friar) on Jul 10, 2002 at 04:57 UTC
    my $s = "hello there <here I am> today is sunny"; if ($s =~ /<([^>]*?)>/) { print "match: $1\n"; }

    --dda

Re: Retrieving text between 2 strings/chars...
by zaimoni (Beadle) on Jul 10, 2002 at 05:00 UTC
    Try:
    my $TestString = "hello there &lt;here I am&gt; today is sunny"; my @Matches = ($TestString =~ m|<(.+?)>|ogs);

    This initializes @Matches with a list of all text strings between an initial < and the first > following it, possibly including later < characters. (In particular, "<<WonderText>>" would have the single match "<WonderText".)

    As for the modifiers (a quick review; cf. the perl documentation for a full explanation)

    • g: global matching
    • o: one-shot (the regex is defined at compile time)
    • s: arbitary string (don't break just because \n is in the string)
    Another modifier that is very practical is:
    • i: case-insensitive

    I generally reach for the documentation if I need anything more complicated than the above.