Skip to content

常用正则模板:复制即用

这一节不废话,直接给模板。找到你的场景,复制,改改,直接用。


验证类模板

手机号(中国大陆)

java
public class PhoneValidation {
    // 基础验证(最常用)
    public static final String PHONE_BASIC = "^1[3-9]\\d{9}$";
    
    // 宽松验证(支持带空格、连字符)
    public static final String PHONE_LOOSE = "^1[3-9][\\s-]?\\d{4}[\\s-]?\\d{4}$";
    
    public static void main(String[] args) {
        String phone = "13812345678";
        System.out.println("基础验证: " + phone.matches(PHONE_BASIC)); // true
        System.out.println("宽松验证: " + phone.matches(PHONE_LOOSE)); // true
        
        // 格式化输出
        String formatted = phone.replaceFirst("(\\d{3})(\\d{4})(\\d{4})", "$1-$2-$3");
        System.out.println("格式化: " + formatted); // 138-1234-5678
        
        // 脱敏处理
        String masked = phone.replaceFirst("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
        System.out.println("脱敏: " + masked); // 138****5678
    }
}

邮箱

java
public class EmailValidation {
    // 简化版(够用)
    public static final String EMAIL_SIMPLE = "^\\w+@\\w+\\.\\w+$";
    
    // 标准版(支持常见邮箱格式)
    public static final String EMAIL_STANDARD = "^[\\w.-]+@[\\w.-]+\\.\\w{2,}$";
    
    // 严格版(带域名后缀长度限制)
    public static final String EMAIL_STRICT = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}$";
    
    public static void main(String[] args) {
        String[] tests = {"user@example.com", "user.name@domain.co.uk", "invalid@", "@example.com"};
        for (String email : tests) {
            System.out.println(email + ": " + email.matches(EMAIL_STANDARD));
        }
    }
}

身份证号

java
public class IdCardValidation {
    // 15位(老版)
    public static final String ID_CARD_15 = "^\\d{15}$";
    
    // 18位(新版)
    public static final String ID_CARD_18 = "^[1-9]\\d{5}(19|20)\\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\\d|3[01])\\d{3}[\\dXx]$";
    
    // 兼容版(15位或18位)
    public static final String ID_CARD_BOTH = "^(\\d{15}|\\d{18}|[1-9]\\d{16}[\\dXx])$";
    
    public static void main(String[] args) {
        String id18 = "110101199003074518";
        String id15 = "110101900307451";
        
        System.out.println("18位: " + id18.matches(ID_CARD_18)); // true
        System.out.println("15位: " + id15.matches(ID_CARD_15)); // true
        
        // 提取生日
        String birthday = id18.replaceAll("(\\d{6})(\\d{8})(\\d{4})", "$2");
        System.out.println("生日: " + birthday); // 19900307
    }
}

URL

java
public class UrlValidation {
    // HTTP/HTTPS URL
    public static final String URL_HTTP = "^https?://[\\w.-]+(:\\d+)?(/[\\w.-]*)*(\\?[\\w=&]*)?$";
    
    // 带协议和路径
    public static final String URL_FULL = "^(https?|ftp)://[^\\s/$.?#].[^\\s]*$";
    
    // 仅域名
    public static final String DOMAIN = "^[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9]?\\.[a-zA-Z]{2,}$";
    
    public static void main(String[] args) {
        String[] urls = {
            "https://example.com",
            "http://sub.domain.co.uk:8080/path",
            "ftp://files.server.com"
        };
        for (String url : urls) {
            System.out.println(url + ": " + url.matches(URL_HTTP));
        }
    }
}

IP 地址

java
public class IpValidation {
    // IPv4(简单版)
    public static final String IP_V4_SIMPLE = "^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$";
    
    // IPv4(严格版,每段 0-255)
    public static final String IP_V4_STRICT = 
        "^((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$";
    
    public static void main(String[] args) {
        String[] ips = {"192.168.1.1", "255.255.255.0", "256.1.1.1", "192.168.1"};
        for (String ip : ips) {
            System.out.println(ip + ": " + ip.matches(IP_V4_STRICT));
        }
        // true, true, false, false
    }
}

日期和时间

java
public class DateTimeValidation {
    // 日期 YYYY-MM-DD
    public static final String DATE_ISO = "^[1-9]\\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\\d|3[01])$";
    
    // 日期 YYYY/MM/DD
    public static final String DATE_SLASH = "^[1-9]\\d{3}/(0[1-9]|1[0-2])/(0[1-9]|[12]\\d|3[01])$";
    
    // 时间 HH:mm:ss
    public static final String TIME_24H = "^([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d$";
    
    // 时间 HH:mm(12小时制,带 AM/PM)
    public static final String TIME_12H = "^(0?[1-9]|1[0-2]):[0-5]\\d\\s?(AM|PM)$";
    
    // 日期时间 ISO 格式
    public static final String DATETIME_ISO = "^[1-9]\\d{3}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}$";
    
    public static void main(String[] args) {
        System.out.println("日期: " + "2026-03-22".matches(DATE_ISO)); // true
        System.out.println("时间: " + "14:30:00".matches(TIME_24H)); // true
    }
}

数字

java
public class NumberValidation {
    public static final String INTEGER = "^-?\\d+$";                    // 整数
    public static final String POSITIVE_INT = "^\\d+$";                 // 正整数
    public static final String NEGATIVE_INT = "^-\\d+$";                // 负整数
    public static final String DECIMAL = "^-?\\d+(\\.\\d+)?$";          // 浮点数
    public static final String POSITIVE_DECIMAL = "^\\d+(\\.\\d+)?$";   // 正浮点数
    public static final String PERCENTAGE = "^\\d+(\\.\\d+)?%$";        // 百分比
    
    // 金额(保留两位小数)
    public static final String MONEY = "^([1-9]\\d{0,12}|0)(\\.\\d{1,2})?$";
    
    public static void main(String[] args) {
        System.out.println("整数: " + "-123".matches(INTEGER)); // true
        System.out.println("浮点: " + "3.14".matches(DECIMAL)); // true
        System.out.println("金额: " + "1234.56".matches(MONEY)); // true
        System.out.println("百分比: " + "99.5%".matches(PERCENTAGE)); // true
    }
}

密码强度

java
public class PasswordValidation {
    // 基础密码(6位以上)
    public static final String PASSWORD_BASIC = "^.{6,}$";
    
    // 中等强度(字母+数字,8位以上)
    public static final String PASSWORD_MEDIUM = "^(?=.*[a-zA-Z])(?=.*\\d)[a-zA-Z\\d]{8,}$";
    
    // 强密码(大小写+数字+特殊字符)
    public static final String PASSWORD_STRONG = 
        "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{8,}$";
    
    // 解释 (?=...) 零宽断言
    // (?=.*[a-z])   包含小写字母
    // (?=.*[A-Z])   包含大写字母  
    // (?=.*\\d)     包含数字
    // (?=.*[@$!])   包含特殊字符
    
    public static void main(String[] args) {
        String[] passwords = {"abc123", "Abc12345", "Abc123!@#"};
        System.out.println("基础: " + passwords[0].matches(PASSWORD_BASIC)); // true
        System.out.println("中等: " + passwords[1].matches(PASSWORD_MEDIUM)); // true
        System.out.println("强密码: " + passwords[2].matches(PASSWORD_STRONG)); // true
    }
}

提取类模板

提取邮箱

java
public class ExtractEmails {
    public static void main(String[] args) {
        String text = "联系邮箱: test@example.com,或工作邮箱 work@company.co.uk";
        
        // 方法1:直接提取
        java.util.regex.Pattern p = java.util.regex.Pattern.compile("\\w+@\\w+\\.\\w+");
        java.util.regex.Matcher m = p.matcher(text);
        while (m.find()) {
            System.out.println("邮箱: " + m.group());
        }
        
        // 方法2:分割后过滤
        String[] parts = text.split("[,\\s]+");
        for (String part : parts) {
            if (part.matches("\\w+@\\w+\\.\\w+")) {
                System.out.println("邮箱: " + part);
            }
        }
    }
}

提取 URL

java
public class ExtractUrls {
    public static void main(String[] args) {
        String text = "官网: https://example.com,备站: http://backup.net/index.html";
        
        java.util.regex.Pattern p = java.util.regex.Pattern.compile("https?://[\\w.-]+(?:/[\\w.-]*)*");
        java.util.regex.Matcher m = p.matcher(text);
        while (m.find()) {
            System.out.println("URL: " + m.group());
        }
    }
}

提取数字

java
public class ExtractNumbers {
    public static void main(String[] args) {
        String text = "iPhone 15 Pro,原价 5999 元,现价 4999 元";
        
        // 提取所有数字
        java.util.regex.Pattern digits = java.util.regex.Pattern.compile("\\d+");
        java.util.regex.Matcher m = digits.matcher(text);
        while (m.find()) {
            System.out.println("数字: " + m.group());
        }
        // 输出: 15, 5999, 4999
        
        // 提取价格(数字+元)
        java.util.regex.Pattern price = java.util.regex.Pattern.compile("(\\d+)元");
        m = price.matcher(text);
        while (m.find()) {
            System.out.println("价格: " + m.group(1));
        }
        // 输出: 5999, 4999
    }
}

提取 HTML 标签内容

java
public class ExtractHtmlContent {
    public static void main(String[] args) {
        String html = "<div>第一段</div><p>第二段</p><span>第三段</span>";
        
        // 提取标签内的文本
        java.util.regex.Pattern p = java.util.regex.Pattern.compile(">([^<]+)<");
        java.util.regex.Matcher m = p.matcher(html);
        while (m.find()) {
            System.out.println("内容: " + m.group(1).trim());
        }
        // 输出: 第一段, 第二段, 第三段
        
        // 提取链接文本
        String linkHtml = "<a href=\"#\">点击这里</a>和<a href=\"/about\">关于我们</a>";
        p = java.util.regex.Pattern.compile("<a[^>]*>([^<]+)</a>");
        m = p.matcher(linkHtml);
        while (m.find()) {
            System.out.println("链接: " + m.group(1));
        }
    }
}

替换类模板

敏感信息脱敏

java
public class MaskingDemo {
    public static void main(String[] args) {
        // 手机号脱敏
        String phone = "13812345678";
        String maskedPhone = phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
        System.out.println("手机: " + maskedPhone); // 138****5678
        
        // 邮箱脱敏
        String email = "test@example.com";
        String maskedEmail = email.replaceAll("(\\w{2})\\w+@(\\w+\\.\\w+)", "$1***@$2");
        System.out.println("邮箱: " + maskedEmail); // te***@example.com
        
        // 身份证脱敏
        String idCard = "110101199003074518";
        String maskedId = idCard.replaceAll("(\\d{6})\\d{8}(\\d{4})", "$1********$2");
        System.out.println("身份证: " + maskedId); // 110101********4518
        
        // 银行卡脱敏(只显示后4位)
        String bankCard = "6222021234567890123";
        String maskedCard = bankCard.replaceAll("\\d(\\d{4})+", m -> {
            String g = m.group();
            return g.substring(0, 1) + "****";
        });
        System.out.println("银行卡: " + maskedCard); // 6****
    }
}

格式化

java
public class FormattingDemo {
    public static void main(String[] args) {
        // 手机号格式化
        String phone = "13812345678";
        String formatted = phone.replaceFirst("(\\d{3})(\\d{4})(\\d{4})", "$1-$2-$3");
        System.out.println("手机: " + formatted); // 138-1234-5678
        
        // 日期格式互换
        String date1 = "2026-03-22";
        String date2 = date1.replaceAll("(\\d{4})-(\\d{2})-(\\d{2})", "$2/$3/$1");
        System.out.println("日期: " + date2); // 03/22/2026
        
        // 驼峰转下划线
        String camel = "userNameFirst";
        String snake = camel.replaceAll("([A-Z])", "_$1").toLowerCase().replaceFirst("^_", "");
        System.out.println("下划线: " + snake); // user_name_first
        
        // 下划线转驼峰
        String underscore = "user_name_first";
        String camelBack = underscore.replaceAll("_([a-z])", m -> m.group(1).toUpperCase());
        System.out.println("驼峰: " + camelBack); // userNameFirst
    }
}

清理文本

java
public class CleanupDemo {
    public static void main(String[] args) {
        // 去除 HTML 标签
        String html = "<p>Hello <b>World</b></p>";
        String plain = html.replaceAll("<[^>]+>", "");
        System.out.println("去标签: " + plain); // Hello World
        
        // 去除特殊字符
        String dirty = "Hello@#$%World123";
        String clean = dirty.replaceAll("[^a-zA-Z0-9]", "");
        System.out.println("去特殊: " + clean); // HelloWorld123
        
        // 合并多余空白
        String messy = "  多个   空白\t\n混合   ";
        String merged = messy.replaceAll("\\s+", " ").trim();
        System.out.println("去空白: " + merged); // 多个 空白 混合
        
        // 提取中文字符
        String mixed = "Hello世界123";
        String chinese = mixed.replaceAll("[^\\u4e00-\\u9fa5]", "");
        System.out.println("中文: " + chinese); // 世界
        
        // 提取英文字母
        String letters = mixed.replaceAll("[^a-zA-Z]", "");
        System.out.println("英文: " + letters); // Hello
    }
}

分割类模板

java
public class SplitDemo {
    public static void main(String[] args) {
        // CSV 分割
        String csv = "apple,banana,cherry";
        String[] fruits = csv.split(",");
        
        // 多分隔符
        String multi = "apple,banana;cherry:date";
        String[] mixed = multi.split("[,;:]");
        
        // 保留尾部空串
        String trailing = "a,b,c,";
        String[] withTrailing = trailing.split(",", -1);
        
        // 按空白分割
        String spaced = "a  b\tc\nd";
        String[] bySpace = spaced.split("\\s+");
        
        // 分割但保留分隔符(正则不够用,需要两步)
        String kv = "name=Alice;age=30";
        String[] pairs = kv.split("(?==)|(?<=;)");
        // [name=, Alice, ;age=, 30]
    }
}

速查表

字符类

[abc]       匹配 a、b、c 之一
[^abc]      匹配除 a、b、c 以外
[a-z]       匹配 a 到 z
\d          匹配数字 [0-9]
\w          匹配 [a-zA-Z0-9_]
\s          匹配空白
.           任意字符(除换行)

量词

*           0 个或多个(贪婪)
+           1 个或多个
?           0 个或 1 个
{n}         恰好 n 个
{n,m}       n 到 m 个
*? +? ??    惰性版本

边界

^           开头
$           结尾
\b          单词边界
\B          非单词边界

分组

(...)       捕获组
(?<name>)   命名捕获
(?:...)     非捕获组
\1 \2       反向引用
|           或运算

常用字符集

[\\u4e00-\\u9fa5]    中文
[a-zA-Z]             英文字母
[a-zA-Z0-9]          英文字母+数字
\\d+                 一个或多个数字

下一节是进阶内容:正则性能优化,让你的正则跑得飞快。

基于 VitePress 构建