简体   繁体   中英

Perl: A maximum in regular expressions?

Here's my code....

#!/usr/bin/perl

$str = 'yaeeeeeeeeeeeeeeeeeeeeah';
$six = 6;
$eight = 8;

if( $str =~ /e{$six,$eight}?/)
{
 print "matches";
}

For some reason this still matches even though the number of e's exceeds the maximum 8. How can I make with regex return false if there are over 8 e's?

Generally its /(?<!e)e{$six,$eight}(?!e)/

Check http://www.perlmonks.org/?node_id=518444

For the really bad case where in the same string, 6-8 e's exist somewhere, but somewhere
else, separately, 20 e's exist, the solution posted won't help.

Example: rrrrrrrreeeeeeerrrrrrrrrrreeeeeeeeeeeeeee

In that case you have to look way ahead for the bad case first e{9} ,
then the good case e{6,8} .

/^(?!.*e{$nine}).*(?<!e)e{$six,$eight}(?!e)/

Your string matches the expressions, because it contains six e's. If you don't want to match, change the expression. For example, you can say that the sequence of e's is not preceded and followed by another e:

/(?<!e) e{$six,$eight} (?!e)/x

These are called negative look-behind and look-ahead assertions.

The question mark after the quantifier makes no difference in such a case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM