java手機(jī)號、郵箱、日期正則表達(dá)式實例代碼
Java正則核心API
Java中用 java.util.regex 包的兩個類:
Pattern:編譯正則表達(dá)式Matcher:執(zhí)行匹配操作
1. 驗證手機(jī)號
String regex = "1[3-9]\\d{9}";
boolean isValid = "18812345678".matches(regex); // true
2. 提取郵箱
String text = "聯(lián)系我:admin@test.com 或 user@qq.com";
Pattern pattern = Pattern.compile("\\w+@\\w+\\.\\w+");
Matcher matcher = pattern.matcher(text);
while(matcher.find()) {
System.out.println(matcher.group()); // 輸出兩個郵箱
}
3. 替換敏感信息
String phone = "手機(jī)號:18812345678";
String masked = phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
// 結(jié)果:手機(jī)號:188****5678
5個必會語法(附Java代碼)
1. 基礎(chǔ)匹配
| 符號 | 說明 | Java示例 | 匹配結(jié)果 |
|---|---|---|---|
\d | 數(shù)字 | "a\\d" | a1, a9 |
\w | 字母數(shù)字下劃線 | "\\w+" | hello, user1 |
. | 任意字符 | "a.c" | abc, a@c |
^ | 開頭 | "^Java" | Java真好用 |
$ | 結(jié)尾 | "end$" | 這是end |
2. 量詞(控制次數(shù))
| 符號 | 說明 | 示例 | 匹配內(nèi)容 |
|---|---|---|---|
? | 0或1次 | "a?" | “”, a |
+ | 1次或多次 | "\\d+" | 1, 123 |
* | 0次或多次 | "a*" | “”, aaaa |
{n} | 精確n次 | "\\d{4}" | 2023 |
3. 字符集合
// 匹配元音字母
Pattern.compile("[aeiou]"); // 匹配 a, e, i 等
// 匹配非數(shù)字
Pattern.compile("[^0-9]"); // 匹配 a, @, # 等
4. 分組提取
String text = "電話:188-1234-5678";
Pattern pattern = Pattern.compile("(\\d{3})-(\\d{4})-(\\d{4})");
Matcher matcher = pattern.matcher(text);
if(matcher.find()) {
System.out.println(matcher.group(1)); // 188
System.out.println(matcher.group(2)); // 1234
System.out.println(matcher.group(3)); // 5678
}
5. 貪婪 vs 非貪婪
// 貪婪模式(默認(rèn))
Pattern.compile("a.*b").matcher("aXXXbYYYb").find(); // 匹配整個字符串
// 非貪婪模式(加?)
Pattern.compile("a.*?b").matcher("aXXXbYYYb").find(); // 只匹配aXXXb
避坑
轉(zhuǎn)義問題:Java中
\要寫兩次// 錯誤寫法:Pattern.compile("\d+"); // 正確寫法: Pattern.compile("\\d+");性能優(yōu)化:復(fù)用
Pattern對象// 不要每次編譯(低效): for(...) { Pattern.matches(regex, text); } // 正確做法: Pattern pattern = Pattern.compile(regex); for(...) { pattern.matcher(text).matches(); }邊界檢查:用
^和$嚴(yán)格匹配// 可能意外匹配子串: "123abc".matches("\\d+"); // false(正確) "123".matches("\\d+"); // true // 錯誤示例:沒有用^$導(dǎo)致誤匹配 "a1b2".matches("\\d+"); // false(正確)
總結(jié)
到此這篇關(guān)于java手機(jī)號、郵箱、日期正則表達(dá)式的文章就介紹到這了,更多相關(guān)java手機(jī)號、郵箱、日期正則表達(dá)式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot 使用 Ehcache 作為緩存的操作方法
這篇文章主要介紹了SpringBoot 如何使用 Ehcache 作為緩存,我們通過添加 Ehcache 依賴、創(chuàng)建 Ehcache 配置文件并在 Spring Boot 應(yīng)用程序的配置文件中啟用 Ehcache 緩存,來配置 Ehcache 緩存,需要的朋友可以參考下2023-06-06
Java基礎(chǔ)之隱式轉(zhuǎn)換vs強(qiáng)制轉(zhuǎn)換
這篇文章主要介紹了Java基礎(chǔ)之隱式轉(zhuǎn)換vs強(qiáng)制轉(zhuǎn)換的相關(guān)資料,需要的朋友可以參考下2015-12-12
Quartz+Spring Boot實現(xiàn)動態(tài)管理定時任務(wù)
最近做項目遇到動態(tài)管理定時任務(wù)的需求,剛拿到這個需求還真不知道從哪下手,經(jīng)過一番思考,終于找出實現(xiàn)思路,接下來通過本文給大家介紹了Quartz+Spring Boot實現(xiàn)動態(tài)管理定時任務(wù)的相關(guān)知識,需要的朋友可以參考下2018-09-09

