Problems? Is your data what you think it is? | |
PerlMonks |
comment on |
( [id://3333]=superdoc: print w/replies, xml ) | Need Help?? |
Is there an easy way to match a range of numbers like 128-255?There is a way, which makes a lot of sense in theory, but of which implementation is rather difficult in Perl5. I have hopes that it will be a lot easier in Perl6. And that mechanism, is to use a regex assertion in Perl code. An assertion is a regex pattern that must match, but which doesn't eat any characters. Well known assertions are anchoring (/^/ and /$/), edge matching (/\b/) and lookahead and lookbehind (eh... see perlre). So how can you do assertion in Perl code? The following solution is based on work by dominus: using the experimental feature of embedding code in a regex, /(?{CODE})/, and use the result of that code as a condition in another experimental feature, conditional matches: /(?(condition)yes-pattern)/ or /(?(condition)yes-pattern|no-pattern)/. A third trick is to use a pattern that can never match: since // always matches, its negation (using negative lookahead), /(?!)/, will always fail. The combination, which acts like an assertion in Perl code, can look like or "COND" and "NOT-COND" represent perl a perl expression that returns a boolean value. It's very ugly, I know. For this example: or
In case you're wondering about the /\b/ assertions: in case our assertion in code fails, it will not prevent backtracking. So without them, if the assertion fails for "350", it would backtrack and try again using "35", and succeed there. That is not what you want, here. Or, with just a trailing /\b/ as in /\d+\b/, it could still succeed for "50". That's why you need both. In reply to Regex assertions in perl code -- Re: regex for classless IP subnets
by bart
|
|