Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re^2: Regex to pull out string within parenthesis that could contain parenthesis

by TheDamian (Vicar)
on Jul 09, 2018 at 21:41 UTC ( [id://1218196]=note: print w/replies, xml ) Need Help??


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:  <%-{-{-{-<

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (4)
As of 2025-05-22 06:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.