Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Need to pull substring between two escape sequences.

by Anonymous Monk
on Mar 30, 2001 at 05:21 UTC ( [id://68256]=perlquestion: print w/replies, xml ) Need Help??

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://68256]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (6)
As of 2024-04-19 10:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found