Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: getting a return code from a looping regular expression

by splinky (Hermit)
on Aug 01, 2000 at 23:43 UTC ( [id://25560]=note: print w/replies, xml ) Need Help??


in reply to getting a return code from a looping regular expression

Utilizing Perl 5.6 regex features, you can do the following:

our $parens; my $re = qr{ ( \( (?{$parens++ if $parens >= 0}) | \) (?{$parens-- if $parens >= 0}) | . )* }x; my $this = 'a(bc(de)fg)h'; my $that = '(a(bc(de)fg)h'; my $other = 'a(bc(de)fg)h)'; my $bla = ')a(bc(de)fg)h)'; $parens = 0; print "this, $parens\n" if $this =~ /$re/; $parens = 0; print "that, $parens\n" if $that =~ /$re/; $parens = 0; print "other, $parens\n" if $other =~ /$re/; $parens = 0; print "bla, $parens\n" if $bla =~ /$re/;

Which prints:

this, 0 that, 1 other, -1 bla, -1

Specifically, -1 indicates that, at some point, an attempt was made to close parens that hadn't been opened. A positive number indicates how many unclosed left parens were encountered.

Thanks, Ilya.

*Woof*

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (6)
As of 2024-04-18 09:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found