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

I need to pull a substring between two escape sequences, I have an escape sequence such as (and only and example) !#HEADER#! and i need to match the beginning !# pull the HEADER into a string and stop at #! but continue searching the string for more !# sequences.
  • Comment on Need to pull substring between two escape sequences.

Replies are listed 'Best First'.
Re: Need to pull substring between two escape sequences.
by Ovid (Cardinal) on Mar 30, 2001 at 17:07 UTC
    Be careful about using something like this:
    my @matches = ($string =~ /!#(.*?)#!/g);
    That will probably not work the way you want it to on the following:
    "123!#45!#678#!90"
    You probably wanted 678, but you get 45!#678 instead. Try something like the following:
    my @matches = ($string =~ /!#((?:[^#!]|#(?!!))*)#!/g );
    See this node for details on this.
Re: Need to pull substring between two escape sequences.
by indigo (Scribe) on Mar 30, 2001 at 05:41 UTC
    Assuming your string isn't perverse (like having an escaped '#!' as part of the string literal):

    my @matches = ($string =~ /!#(.*?)#!/g);

    The .*? insures non-greedy matching and the /g applies it across the entire string. The params "capture" your string, and a list of all matching strings will be returned.