regex - How does this regular expression work? -


from this article,

/^1?$|^(11+?)\1+$/ checks whether number(its value in unary) prime or not.

using this, perl -l -e '(1 x $_) !~ /^1?$|^(11+?)\1+$/ && print while ++$_;' returns list of prime numbers.

i not have enough experience perl, understand regular expression true number not prime. so, if print numbers not produce true expression, have list of prime numbers. thats perl query trying do.

about regex part,

^1?$ part counting 1 not prime

^(11+?)\1+$ matching not prime numbers starting 4.


what not understand why ? in regex needed @ all. according me /^1$|^(11+)\1+$/ should fine , actually

perl -l -e '(1 x $_) !~ /^1$|^(11+)\1+$/ && print while ++$_;' gives me same set of prime numbers.

is there flaw in understanding of regular expression? why ?s needed?

isn't ? supposed match 0 or 1 occurrence of expression preceding it?

the first ? matching empty string (i.e. 0) non-prime. if don't care whether regexp matches 0, it's not necessary.

the second ? efficiency. + "greedy", means matches many characters available, , backtracks if rest of regexp fails match. +? makes non-greedy, matches 1 character, , tries matching more if rest of regexp fails match. (see the quantifiers section of perlre more greedy vs. non-greedy matching.)

in particular regexp, (11+?) means tests divisibility 2 ('11'), 3 ('111'), 4, etc. if used (11+), test divisibility n (the number itself), n-1, n-2, etc. since divisor must no greater n/2, without ? waste time testing lot of "potential" divisors can't possibly work. still match non-prime numbers, more slowly. (also, $1 largest divisor instead of smallest one.)


Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -