in reply to Re^3: Matching a string in a parenthesized block (regex help)
in thread Matching a string in a parenthesized block (regex help)

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 }.

Replies are listed 'Best First'.
Re^5: Matching a string in a parenthesized block (regex help)
by LanX (Saint) on Mar 06, 2021 at 14:06 UTC
    > s .*? is searching for any character including the closing brace }.

    Yes, that's why I added an alternative.

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

      Thanks I think I got the right regex now, this seems to work

      m/(ASDF_$arg \{)([^}]*?)magic(.*?)(\})/s

      That is exactly what I wanted.