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

Hi, How to get the contents between two specified text i.e. contents between Text1 and Text2 Thanks in advance

Replies are listed 'Best First'.
Re: Contents b/w two given text
by reasonablekeith (Deacon) on Aug 25, 2005 at 09:58 UTC
    my $string = "blah text1 you mean something like this? text2 blah blah +"; if ($string =~ m/text1(.*?)text2/) { print $1; }
    ---
    my name's not Keith, and I'm not reasonable.
      I think you want a modifier as part of the regular expression if you want to match text that includes a line break.
    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: Contents b/w two given text
by samizdat (Vicar) on Aug 25, 2005 at 12:40 UTC
    Or, expanded to have your texts taken from variables:

    #!/usr/local/bin/perl -w use strict; my $string = "blah text1 you mean something like this? text2 blah blah +"; my $t1 = 'text1'; my $t2 = 'text2'; my $match = $t1 . '(.*?)' . $t2; if ($string =~ m/$match/s) { print $1; }
      Unless you are certain that $t1 and $t2 have no special regular expression characters, like [ ] . * ? + ( ) \ ^ $ ? and so on, you should clip them with \Q \E.
      #!/usr/local/bin/perl -w use strict; my $string = "blah text1 you mean more like this? text2 blah"; my $t1 = 't(e*x+t)1'; my $t2 = 't[ex]*t?2'; my $match = qr/\Q$t1\E(.*?)\Q$t2/; print "no match\n" unless $string =~ m/$match/s;

      --
      [ e d @ h a l l e y . c c ]

Re: Contents b/w two given text
by anonymized user 468275 (Curate) on Aug 25, 2005 at 15:50 UTC
    Could define and redefine the record separator to be text1 and text2 respectively, e.g.:
    perl -e '$/="text1"; <>; $/="text2"; $_=<>; chomp; print "$_\n";' < fi +le

    One world, one people