tags:

views:

208

answers:

1

I've read this article where the /^1?$|^(11+?)\1+$/ Perl regex is used to test if a number is prime or not.

Process:

s = '1' * your_number

If s matchs the regex, then it's not prime. If it doesn't, it's prime.

How would you translate that regex to Python's re module?

+3  A: 

It works as is (except without the slashes at the edges, which aren't needed in Python):

pattern = r'^1?$|^(11+?)\1+$'
re.match(pattern, '1'*10)    #matches
re.match(pattern, '1'*11)    #doesn't match

The only nonstandard regex feature needed here is backreferences (\1), and these are supported in both Perl and Python.

interjay
Thanks, I was having problems because I forgot the r of raw
Juanjo Conti
can anyone explain why the deleted answer http://stackoverflow.com/questions/2225027/is-prime-function-via-regex-in-python-from-perl/2225069#2225069 is wrong (assuming it was deleted because it was wrong)?
ysth
I saw it. It wasn't wrong.
Juanjo Conti