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 (Priest)
on Jul 09, 2018 at 21:41 UTC ( #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 (Bishop) 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
Node Status?
node history
Node Type: note [id://1218196]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (8)
As of 2019-10-21 10:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?