---
title: "正则表达式 匹配 数字 范围"
author: "lippeng"
date: "2011-05-10T14:20:28Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2011-07-21T11:18:55Z"
id: 1038986
url: "https://lippeng.iteye.com/blog/1038986"
---

今天要写一个正则表达式，来做前端校验。主要部分是 用来匹配1~4095的数字。

 

现在就以这个为例，说一下表示范围的正则怎么写。

 

1、只有1~3位数字，即数字范围：1~999。

 

分析：第1个数字是1~9，后面的可以出现0~9的数字，最多2位。于是，就有了下面的字符串：

 

"\[1-9]\\\\d{0,2}+"

 

2、4位数的，要小于等于4095，即数字范围：1000~4095。

 

分析：第1位，可以是1~4；第2位，依赖第1位，当第1位是4的时候，第2位只能是0；同理，第3位依赖第2位；第4位依赖第3位。所以，就有了以下代码：

 

"\[1-4]\\\\d(?&lt;!4\[1-9])\\\\d\\\\d(?&lt;!409\[6-9])"

 

这里用的是非捕获`(?<!`*X*`)` *X*，通过零宽度的负 lookbehind 来实现的。

 

完整代码如下：

 

 

```
package com.lippeng.helloworld;

import java.io.UnsupportedEncodingException;

public class HelloWorld {

    public static void main(String[] args) throws UnsupportedEncodingException {

        // 1~4095
        String regex = "[1-9]\\d{0,2}+|[1-4]\\d(?<!4[1-9])\\d\\d(?<!409[6-9])";

        String[] strArray = { "4094", "4095", "4096", "5000", "4000", "900", "10", "9", "0", "1", "-1", "a", "@" };

        for (String str : strArray) {
            System.out.println(str + " " + str.matches(regex));
        }

    }
}
```

 

 

测试结果：

 

 

```
4094 true
4095 true
4096 false
5000 false
4000 true
900 true
10 true
9 true
0 false
1 true
-1 false
a false
@ false
```