http://qs321.pair.com?node_id=1218196


in reply to Re: Regex to pull out string within parenthesis that could contain parenthesis (updated)
in thread Regex to pull out string within parenthesis that could contain parenthesis

Here's a variation on the above solution, using named recursive subpatterns and named captures.
Nowadays I write all my non-trivial regexes this way.
use 5.010; my $source = 'function convert(beg string, end string, read_date date, + step char(6)) returns (date, date, char(1))'; my $matched = $source =~ m{ \A \s*+ (?<access> private | public )?+ \s*+ (?<keyword> function | report ) \s*+ (?<name> (?&identifier) ) \s*+ (?<params> (?&list) ) \s*+ (returns \s*+ (?<returns> (?&list) ) )?+ \s*+ \z (?(DEFINE) (?<identifier> [^\W\d]\w*+ ) (?<list> [(] [^()]*+ (?: (?&list) [^()]*+ )*+ [)] ) ) }xms; if ($matched) { my %components = %+; use Data::Dumper 'Dumper'; say Dumper \%components; } else { say 'parse failed'; }
which outputs:
$VAR1 = { keyword => 'function', name => 'convert', params => '(beg string, end string, read_date date, step char(6))', returns => '(date, date, char(1))', };

Replies are listed 'Best First'.
Re^3: Regex to pull out string within parenthesis that could contain parenthesis
by AnomalousMonk (Archbishop) on Jul 09, 2018 at 21:57 UTC

    I had entirely forgotten about named captures and  (?(DEFINE)...) — a much better (regex) approach.


    Give a man a fish:  <%-{-{-{-<