jlf has asked for the wisdom of the Perl Monks concerning the following question:
I've been looking for a way to make a regex either match or fail based on arbitrary tests of its backreferences. I've read perldoc perlre and I've got something working but it's fairly ugly and it seems that there should be a cleaner way to accomplish it.
In this simple example, I'm checking for percentages greater than 91:
To comment the second RE above (I know about /x but there seems to be some strange interaction between it and ?( on my system):$_ = "it's 94% fat-free!"; # a string that should match # the following code works but the logic is outside the RE print "match\n" if (/(\d{1,3})%/, $1>91); # the following code also works but is offensive print "match\n" if /(\d{1,3})%(?(?{$1>91})(?:.*)|(?!.*))/;
Any suggestions on doing this more elegantly?/(\d{1,3})% # find a percentage to match (?( # begin conditional construct ?{$1>91}) # return value of a code block can be used to test (?:.*) # RE to use if true -- this always-true RE makes entire RE m +atch | (?!.*))/ # RE to use if false -- this always-false RE makes entire RE + fail
Josh
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Conditionals within Regex
by sauoq (Abbot) on Aug 09, 2002 at 19:54 UTC | |
by jlf (Scribe) on Aug 09, 2002 at 21:27 UTC | |
|
Re: Conditionals within Regex
by blakem (Monsignor) on Sep 16, 2002 at 01:56 UTC | |
by jlf (Scribe) on Sep 16, 2002 at 04:24 UTC | |
|
Re: Conditionals within Regex
by japhy (Canon) on Sep 16, 2002 at 03:07 UTC |