in reply to Regex to pull out string within parenthesis that could contain parenthesis
Here's another, more factored example of the use of recursive subpatterns (introduced with Perl version 5.10):
c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le "use 5.010; ;; my $s = 'function convert(beg string, end string, read_date date, step char +(6)) returns (date, date, char(1))'; ;; my $rx_paren = qr{ ( [(] (?: [^()]*+ | (?-1))* [)] ) }xms; my $rx_identifier = qr{ \w+ }xms; ;; my $parsed_ok = my @ra = $s =~ m{ \A \s* (private|public)? \s* (function|report) \s* ($rx_identifier) \s* $rx_paren \s* ((returns) \s* $rx_paren)? \s* \z }xms; ;; if ($parsed_ok) { dd @ra; } else { print 'parse failed'; } " ( undef, "function", "convert", "(beg string, end string, read_date date, step char(6))", "returns (date, date, char(1))", "returns", "(date, date, char(1))", )
Update: The (private|public)? \s* sub-expression in the above m// should probably be something like (untested)
((?: private | public) \s)? \s*
because, e.g., public looks too much like function or report that would always follow it and requires some delimitation.
Give a man a fish: <%-{-{-{-<
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Regex to pull out string within parenthesis that could contain parenthesis
by TheDamian (Vicar) on Jul 09, 2018 at 21:41 UTC | |
by AnomalousMonk (Archbishop) on Jul 09, 2018 at 21:57 UTC |