---
title: "正则表达式的奇技淫巧-正则表达式判断素数，判断方程是否有解"
author: "wjm251"
date: "2010-07-24T00:55:30Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2010-07-27T10:03:37Z"
id: 720160
url: "https://appofis.iteye.com/blog/720160"
---

首先申明，思想来自下面两个网页
http://coolshell.cn/?p=2704
http://blog.stevenlevithan.com/archives/algebra-with-regexes
我自己改造成python代码并加了下注解，遂成。
也许数据大了性能有问题，但确实太酷了。


```python

#coding=utf-8
import re
def isPrime(num):
    pa = re.compile(r"""^1?$ #匹配空串或1
    |
    ^
    (11+?)#匹配1再加1个或多个1（这里是不贪婪的，可能贪婪的还需要往后看效率底点）
    \1+   #将上述匹配到的组再重复一次或多次，这正好是合数的算法
    $""",re.VERBOSE)
    return pa.match("1"*num) is None
for n in xrange(100):#输出100内的素数
    if isPrime(n):
        print n,
```



```python

#coding=utf-8
#判断方程11x + 2y + 5z = 115是否有解
import re
pa = re.compile(r"^(.*)\1{10}(.*)\2{1}(.*)\3{4}$")
ma = pa.match("1"*115)
if ma!=None:
    print ma.groups()

```