Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Matching a string in a parenthesized block (regex help)

by LanX (Saint)
on Mar 05, 2021 at 22:40 UTC ( [id://11129179]=note: print w/replies, xml ) Need Help??


in reply to Matching a string in a parenthesized block (regex help)

The best answer depends on the things you haven't told us, like
  • are blocks never nested?
  • do they always finish in a single } per line?

If both is true use the flip-flop operator .. to match start and end of a block.

Use a normal regex to match the insides.

edit

if( /block-start/ .. /block-end/ ) { $block .= $line; $hit = 1 if /match-plz/; } else { print $block if $hit; $block = $hit = undef; # reset }

Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery

Replies are listed 'Best First'.
Re^2: Matching a string in a parenthesized block (regex help)
by maxamillionk (Acolyte) on Mar 06, 2021 at 14:23 UTC
    I must admit my knowledge is not advanced enough to understand the significance of the .= operator here. What is the reason behind adding strings to a string here? Not sure how to implement this solution.
      I already linked to the docs for the Flip-Flop operator

      Here an implementation

      Please note how ...

      • it avoids slurping the whole (potentially huge) file into RAM
      • it's self documenting (well better than one big regex)
      • you can now easily add more complicated tests when maintaining

      use strict; use warnings; my $section; my $hit; while (<DATA>) { my $start = /^ASDF \{\s*$/; #(2) my $end = /^\}\s*$/; if ($start .. $end) { $section .= $_; $hit = 1 if /foo_match/; } if ($end and $hit) { print $section; $section = $hit = ""; # reset (1) } } __DATA__ ASDF { tmp foo_match tmp } string2 { tmp } ASDF { tmp bar_match tmp }

      NB:

      • 1) you can also exit instead of resetting
      • 2) allowing potential "invisible" whitespace \s* at the end makes it more robust

      Cheers Rolf
      (addicted to the Perl Programming Language :)
      Wikisyntax for the Monastery

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (4)
As of 2024-04-18 03:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found