http://www.perlmonks.org?node_id=818847


in reply to how to write a multi-line regex

You may want to take a look at perlre and perlretut. I usually pick something such as below (admittedly picked it up from Perl Best Practices by Damian Conway). I like to use the 'xms' modifiers:

my $line = qr{ \A # Start of string \s* # Leading blanks \w+ # Key \s* \w+ # Value \s* # Trailing blanks \z # End of string }xms;

Alternatively, I use Regexp::Common as well if I want to build something up from components. It's not really what you were asking, but it may be handy.

Replies are listed 'Best First'.
Re^2: how to write a multi-line regex
by zerocred (Beadle) on Jan 22, 2010 at 08:06 UTC
    Thanks for the replies. I see it now - I didn't have the /x on the end - or I put it in the $regex (but incorrectly). So either put the /x on the end where it is used in the code or put the whole thing "m/abc/x" in $regex. Ta much.

      If you want to put the x inside the regex you can do it like this (ripping off Utilitarian's code):

      my $regex =qr{(?x) ^(\w*)?\s #A comment (\w*)?\s # an other (\w*)?\s # and again (?:([A-Z]*)\s)? # all the way through (\d+)\* # so that the homicidal psychopath (?:([0-9+]+)[>])? # who knows where you live ([0-9+]+)\s. # and will have to maintain this code (\d*) # will think well of you };

      Note that the (?x) must immediately follow the first regex delimiter otherwise the whitespace before will be a literal part of the pattern (this was not the case with earlier Perl versions, 5.6 IIRC) and note also that using qr{...} creates a compiled regex which you assign to a scalar for later use. The nice thing about the (?x) syntax is the ability to switch behaviours on and off for different regions in your pattern whereas the /.../x modifier applies to the whole pattern. This is probably more useful with something like case insensitivity and such use is illustrated in this reply in a thread started by Win.

      I hope this is helpful.

      Cheers,

      JohnGG

        Thanks John, that's great - the (?x) is a great little trick! I used this technique.