---
title: "使用正则表达式判断一个数是否为素数"
author: "MouseLearnJava"
date: "2014-11-23T13:35:06Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2014-11-23T13:35:06Z"
id: 2159429
url: "https://mouselearnjava.iteye.com/blog/2159429"
---

正则表达式能够用于判断一个数是否为素数，这个以前完全没有想过。

本文将给出一个使用正则判断素数的方法，该正则表达式来源于网页[http://stackoverflow.com/questions/2795065/how-to-determine-if-a-number-is-a-prime-with-regex](http://stackoverflow.com/questions/2795065/how-to-determine-if-a-number-is-a-prime-with-regex)  
正则表达式为**.{0,1}|(.{2,})\\\\1+**

正则含义

```
.{0,1}                        ### The first part of the alternation matches String of length 0 or 1 (NOT prime by definition)
|                             ### Or 
(.{2,})\\1+                   ### The second part of the alternation, a variation of the regex explained above, matches String of length n that is "a multiple" of a 
                                  String of length k >= 2 (i.e. n is a composite, NOT a prime). 
```

代码如下：

```
public class CheckPrimeUsingRegex {

	public static boolean isPrime(int n) {
		return !new String(new char[n]).matches(".{0,1}|(.{2,})\\1+");
	}
}
```

   
测试输出100以内的所有素数

```
public class CheckPrimeUsingRegexTest {
	public static void main(String[] args) {
		for (int i = 0; i < 100; i++) {
			if (CheckPrimeUsingRegex.isPrime(i)) {
				System.out.println(i);
			}
		}
	}
}
```

 

```
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
```

这种判断素数的方法适合小一点的数，并不适合判断比较大的数值，数字很大时容易产生OutOfMemoryError。

```
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
	at java.util.Arrays.copyOf(Unknown Source)
	at java.lang.String.<init>(Unknown Source)
	at CheckPrimeUsingRegex.isPrime(CheckPrimeUsingRegex.java:13)
	at CheckPrimeUsingRegexTest.main(CheckPrimeUsingRegexTest.java:4)
```

 

原文地址 [http://thecodesample.com/?p=1006](http://thecodesample.com/?p=1006)

更多的例子请访问 [http://thecodesample.com/](http://thecodesample.com/)