This is PerlMonks "Mobile"

Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  


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

I played around with your regex, what exactly is wrong, except that you didn't slurp it all into $file?

!/usr/bin/perl use warnings; use strict; my $file = "/path/to/file.txt"; local $/; # added after post my $content = <DATA>; if ( $content =~ m/(ASDF \{)(.*?)plz_match(.*?)(\})/s ) { print "Matched: <<< $& >>>\n"; } else { print "No match: |$content|\n"; } __DATA__ ASDF { tmp plz_match tmp } string2 { tmp } string3 { tmp }

Matched: <<< ASDF { tmp plz_match tmp } >>>

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 00:22 UTC

    Now that you mention it, I think the slurp mode fixed my little program.

    *edit*

    Actually no it seems like it wants to match greedily all the way down to the end of the file... I will check the other responses. For instance it wants to look outside ASDF and will match the other blocks if it has plz_match

      Look at my regex, I made both .*? non-greedy.

      jwkrahn's solution isn't bad either, if your records are that consistent.

      Edit

      Though [^}]*? is certainly better for more complex input.

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

        Sorry I should have clarified a bit more. Here is an example file I'm working with.

        ASDF_ONE { magic tmp tmp } ASDF_TWO { tmp tmp tmp } string3 { tmp tmp magic }

        Some sections have a common prefix, like ASDF_. I want a function in my program to scan a specific section for the magic word using an argument. The function returns true if word is found, else returns false. See code below for how I want to structure this:

        use warnings; use strict; my $file = "/path/to/file.txt"; sub has_word { my $arg = $_[0]; local $/; open FILE, '<', $file; while ( <FILE> ) { if ( m/(ASDF_$arg \{)(.*?)magic(.*?)(\})/s ) { close FILE; return 1; } else { close FILE; return 0; } } } sub main { if (has_word("ONE")) { print "ONE already has the word.\n"; } else { print "ONE does not have the word.\n"; } if (has_word("TWO")) { print "TWO already has the word.\n"; } else { print "TWO does not have the word.\n"; } } main;

        The output I get is:

        ONE already has the word. TWO already has the word.

        I think this .*? is searching for any character including the closing brace }.