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
In reply to Conditionals within Regex by jlf
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |