wordpress圖片站點(diǎn)網(wǎng)站制作網(wǎng)站推廣
正則表達(dá)式
1.1 正則表達(dá)式的概念及演示
在Java中,我們經(jīng)常需要驗(yàn)證一些字符串,例如:年齡必須是2位的數(shù)字、用戶名必須是8位長(zhǎng)度而且只能包含大小寫字母、數(shù)字等。正則表達(dá)式就是用來驗(yàn)證各種字符串的規(guī)則。它內(nèi)部描述了一些規(guī)則,我們可以驗(yàn)證用戶輸入的字符串是否符合這些規(guī)則。
示例:QQ號(hào)碼驗(yàn)證
先看一個(gè)不使用正則表達(dá)式的例子:驗(yàn)證QQ號(hào)碼是否符合以下規(guī)則:
- QQ號(hào)碼必須是5-15位長(zhǎng)度。
- 必須全部是數(shù)字。
- 首位不能為0。
package com.rckivy.demo;public class RegexDemo1 {public static void main(String[] args) {String qq = "1234567890";System.out.println(checkQQ(qq));// 使用正則表達(dá)式簡(jiǎn)化驗(yàn)證System.out.println(qq.matches("[1-9]\\d{4,14}"));}// 自定義驗(yàn)證QQ號(hào)的方法,不使用正則表達(dá)式public static boolean checkQQ(String qq) {int len = qq.length();if (len < 5 || len > 15) { return false;}if (qq.startsWith("0")) { return false;}for (int i = 0; i < len; i++) {char c = qq.charAt(i);if (c < '0' || c > '9') {return false;}}return true;}
}
使用正則表達(dá)式簡(jiǎn)化驗(yàn)證:
public class RegexDemo {public static void main(String[] args) {String qq = "1234567890";System.out.println(qq.matches("[1-9]\\d{4,14}"));}
}
這里的正則表達(dá)式 [1-9]\\d{4,14}
表示:
[1-9]
:首位不能為0,只能是1-9。\\d{4,14}
:接下來4到14位必須是數(shù)字,總長(zhǎng)度為5到15位。
1.2 正則表達(dá)式 - 字符類
正則表達(dá)式中,可以使用字符類來定義匹配規(guī)則,常見的字符類包括:
[abc]
:表示a、b、c中任意一個(gè)字符。[^abc]
:表示除a、b、c以外的任意字符。[a-z]
:表示a到z的所有小寫字母。[A-Z]
:表示A到Z的所有大寫字母。[0-9]
:表示0到9的數(shù)字。[a-zA-Z0-9]
:表示a到z、A到Z和0到9的任意一個(gè)字符。[a-dm-p]
:表示a到d或m到p之間的任意字符。
代碼示例:
package com.rckivy.demo;public class RegexDemo2 {public static void main(String[] args) {// 使用字符類匹配System.out.println("a".matches("[abc]")); // trueSystem.out.println("z".matches("[abc]")); // falseSystem.out.println("x".matches("[^abc]")); // true// 匹配字母范圍System.out.println("z".matches("[a-zA-Z]")); // trueSystem.out.println("A".matches("[a-zA-Z]")); // trueSystem.out.println("0".matches("[a-zA-Z]")); // false// 匹配多個(gè)字符System.out.println("z".matches("[a-zA-Z][a-zA-Z]")); // falseSystem.out.println("ab".matches("[a-zA-Z][a-zA-Z]")); // true}
}
1.3 正則表達(dá)式 - 邏輯運(yùn)算符
正則表達(dá)式中使用邏輯運(yùn)算符可以靈活地構(gòu)造匹配模式:
&&
:并且,表示組合多個(gè)條件。|
:或者,表示在多個(gè)條件之間選擇一個(gè)。\
:轉(zhuǎn)義字符,用于轉(zhuǎn)義特殊字符。
代碼示例:
public class RegexDemo {public static void main(String[] args) {// 邏輯運(yùn)算符匹配String regex = "[a-z&&[^aeiou]]ad"; // 匹配以小寫輔音字符開頭,后跟adSystem.out.println("bad".matches(regex)); // trueSystem.out.println("had".matches(regex)); // trueregex = "[a|e|i|o|u]ad"; // 匹配以元音字符開頭,后跟adSystem.out.println("oad".matches(regex)); // trueSystem.out.println("had".matches(regex)); // false}
}
1.4 正則表達(dá)式 - 預(yù)定義字符
預(yù)定義字符類簡(jiǎn)化了常見字符組的書寫,常見的預(yù)定義字符類包括:
.
:匹配任意字符(除了換行符)。\d
:匹配任意數(shù)字字符(0-9)。\D
:匹配任意非數(shù)字字符。\s
:匹配空白字符(空格、制表符等)。\S
:匹配非空白字符。\w
:匹配單詞字符(字母、數(shù)字、下劃線)。\W
:匹配非單詞字符。
代碼示例:
public class RegexDemo {public static void main(String[] args) {// 匹配單個(gè)字符System.out.println("a".matches("\\w")); // true, 匹配單詞字符System.out.println("你".matches("\\w")); // false, 不是字母或數(shù)字System.out.println("3".matches("\\d")); // true, 匹配數(shù)字字符System.out.println(" ".matches("\\s")); // true, 匹配空格System.out.println("$".matches("\\W")); // true, 匹配非單詞字符}
}
1.5 正則表達(dá)式 - 數(shù)量詞
數(shù)量詞用于指定字符或字符組的重復(fù)次數(shù):
X?
:0次或1次。X*
:0次到多次。X+
:1次或多次。X{n}
:恰好n次。X{n,}
:至少n次。X{n,m}
:n到m次。
代碼示例:
public class RegexDemo {public static void main(String[] args) {// 數(shù)量詞匹配System.out.println("1234".matches("\\d{4}")); // true, 正好4位數(shù)字System.out.println("123".matches("\\d{2,4}")); // true, 2到4位數(shù)字System.out.println("a".matches("\\w+")); // true, 至少1個(gè)字母System.out.println("".matches("\\w*")); // true, 0個(gè)或更多字母}
}
1.6 正則表達(dá)式練習(xí)
需求:
- 請(qǐng)編寫正則表達(dá)式驗(yàn)證用戶輸入的手機(jī)號(hào)碼是否符合規(guī)則:
- 手機(jī)號(hào)碼必須是以1開頭的11位數(shù)字。
- 驗(yàn)證手機(jī)號(hào)碼示例:
13112345678
、13712345667
。
代碼示例:
public class RegexDemo {public static void main(String[] args) {String regex = "1[3-9]\\d{9}"; // 匹配手機(jī)號(hào)碼System.out.println("13112345678".matches(regex)); // trueSystem.out.println("13712345667".matches(regex)); // trueSystem.out.println("13945679027".matches(regex)); // trueSystem.out.println("139456790271".matches(regex)); // false}
}
1.7 正則表達(dá)式練習(xí)2
需求:
-
驗(yàn)證用戶名是否滿足要求:
- 用戶名由大小寫字母、數(shù)字和下劃線組成,長(zhǎng)度為4-16位。
-
驗(yàn)證身份證號(hào)碼:
- 簡(jiǎn)單要求:18位,前17位為數(shù)字,最后一位可以是數(shù)字或大寫/小寫的
x
。 - 復(fù)雜要求:嚴(yán)格按照身份證號(hào)碼的格式進(jìn)行驗(yàn)證,包括出生日期、地區(qū)代碼等。
- 簡(jiǎn)單要求:18位,前17位為數(shù)字,最后一位可以是數(shù)字或大寫/小寫的
用戶名驗(yàn)證
用戶名的正則表達(dá)式規(guī)則:
String regex1 = "\\w{4,16}"; // \w 表示字母、數(shù)字或下劃線,{4,16} 表示長(zhǎng)度為4到16位
System.out.println("zhangsan".matches(regex1)); // true
System.out.println("user1234".matches(regex1)); // true
System.out.println("u".matches(regex1)); // false
System.out.println("$123".matches(regex1)); // false
簡(jiǎn)單身份證號(hào)碼驗(yàn)證
身份證號(hào)的規(guī)則:
- 前17位為數(shù)字。
- 最后一位可以是數(shù)字,也可以是字母X(不區(qū)分大小寫)。
String regex2 = "[1-9]\\d{16}[\\dXx]"; // 前17位為數(shù)字,最后一位為數(shù)字或X
System.out.println("41080119930228457x".matches(regex2)); // true
System.out.println("510801197609022309".matches(regex2)); // true
System.out.println("15040119810705387X".matches(regex2)); // true
System.out.println("12345678901234567X".matches(regex2)); // false (開頭不能為0)
復(fù)雜身份證號(hào)碼驗(yàn)證
在更復(fù)雜的身份證號(hào)碼規(guī)則中,需要驗(yàn)證更多細(xì)節(jié),包括:
- 前6位表示地區(qū)代碼(不能以0開頭)。
- 第7到14位表示出生日期,年份為18、19或20開頭,月份為01到12,日期為01到31。
- 最后一位同樣可以是數(shù)字或字母X。
String regex3 = "[1-9]\\d{5}(18|19|20)\\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\\d|3[01])\\d{3}[\\dXx]";
System.out.println("41080119930228457x".matches(regex3)); // true
System.out.println("510801197609022309".matches(regex3)); // true
System.out.println("15040119810705387X".matches(regex3)); // true
System.out.println("130133197204039024".matches(regex3)); // true
1.8 本地?cái)?shù)據(jù)爬取
Pattern 和 Matcher
在Java中,Pattern
類用來表示正則表達(dá)式,Matcher
類則是正則表達(dá)式應(yīng)用到某個(gè)文本后的匹配結(jié)果對(duì)象。我們可以使用它們從大文本中提取出符合正則表達(dá)式的子串。
示例:從文本中爬取特定模式的數(shù)據(jù)
需求:
有如下文本,請(qǐng)從中爬取所有 JavaXX
的內(nèi)容(XX代表任意數(shù)字)。
public class RegexDemo6 {public static void main(String[] args) {String str = "Java自從95年問世以來,經(jīng)歷了很多版本," +"目前企業(yè)中用的最多的是Java8和Java11," +"下一個(gè)長(zhǎng)期支持版本是Java17,相信在未來不久Java17也會(huì)逐漸登上歷史舞臺(tái)";// 1. 創(chuàng)建正則表達(dá)式的Pattern對(duì)象Pattern p = Pattern.compile("Java\\d{0,2}");// 2. 獲取Matcher對(duì)象Matcher m = p.matcher(str);// 3. 循環(huán)查找匹配的內(nèi)容while (m.find()) {System.out.println(m.group());}}
}
在上面的示例中,Java\\d{0,2}
匹配以 “Java” 開頭,后面跟0到2個(gè)數(shù)字的字符串。m.find()
方法每次查找下一個(gè)符合條件的字符串,直到查找完畢。
1.9 網(wǎng)絡(luò)數(shù)據(jù)爬取
有時(shí)候,我們不僅需要從本地?cái)?shù)據(jù)中提取信息,還需要從網(wǎng)絡(luò)上的網(wǎng)頁(yè)中提取數(shù)據(jù)。這種場(chǎng)景下,可以通過Java中的 URL
和 URLConnection
來獲取網(wǎng)頁(yè)內(nèi)容,然后使用正則表達(dá)式提取所需的數(shù)據(jù)。
示例:從網(wǎng)頁(yè)中爬取身份證號(hào)碼
需求:
從指定的網(wǎng)頁(yè)中提取所有的身份證號(hào)碼。
import java.io.*;
import java.net.*;
import java.util.regex.*;public class RegexDemo7 {public static void main(String[] args) throws IOException {// 創(chuàng)建URL對(duì)象,連接到網(wǎng)頁(yè)URL url = new URL("https://example.com/sample_page.html");URLConnection conn = url.openConnection();// 使用BufferedReader讀取網(wǎng)頁(yè)內(nèi)容BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));String line;// 創(chuàng)建匹配身份證號(hào)的正則表達(dá)式String regex = "[1-9]\\d{16}[\\dXx]";Pattern pattern = Pattern.compile(regex);// 逐行讀取網(wǎng)頁(yè)內(nèi)容,查找匹配項(xiàng)while ((line = br.readLine()) != null) {Matcher matcher = pattern.matcher(line);while (matcher.find()) {System.out.println(matcher.group());}}br.close();}
}
這個(gè)程序會(huì)從網(wǎng)頁(yè)中逐行讀取內(nèi)容,并使用正則表達(dá)式 [1-9]\\d{16}[\\dXx]
匹配身份證號(hào)碼。
1.10 正則表達(dá)式爬取數(shù)據(jù)練習(xí)
需求:
從給定的文本中提取出所有的座機(jī)號(hào)碼、郵箱、手機(jī)號(hào)和熱線電話。
文本內(nèi)容:
來學(xué)校學(xué)習(xí)Java,手機(jī)號(hào):18512516758,18512508907,或者聯(lián)系郵箱:boniu@itbright.cn,
座機(jī)電話:010-36517895,010-98951256,郵箱:bozai@itbright.cn,
熱線電話:400-618-9090,4006189090
代碼實(shí)現(xiàn):
public class RegexDemo8 {public static void main(String[] args) {String s = "來學(xué)校學(xué)習(xí)Java,手機(jī)號(hào):18512516758,18512508907," +"或者聯(lián)系郵箱:boniu@itbright.cn,座機(jī)電話:010-36517895,010-98951256," +"郵箱:bozai@itbright.cn,熱線電話:400-618-9090,4006189090";// 正則表達(dá)式String regex = "(1[3-9]\\d{9})" + // 手機(jī)號(hào)"|(\\w+@[\\w&&[^_]]{2,6}(\\.[a-zA-Z]{2,3}){1,2})" + // 郵箱"|(0\\d{2,3}-?[1-9]\\d{4,9})" + // 座機(jī)"|(400-?\\d{3}-?\\d{4})"; // 熱線電話Pattern p = Pattern.compile(regex);Matcher m = p.matcher(s);// 逐一查找并輸出結(jié)果while (m.find()) {System.out.println(m.group());}}
}
1.11 按需求爬取特定數(shù)據(jù)
需求:
給定一段文本,爬取出所有符合條件的Java
版本信息。
文本內(nèi)容:
Java自從95年問世以來,經(jīng)歷了很多版本,目前企業(yè)中用的最多的是Java8和Java11,
因?yàn)檫@兩個(gè)是長(zhǎng)期支持版本,下一個(gè)長(zhǎng)期支持版本是Java17,相信在未來不久Java17也會(huì)逐漸登上歷史舞臺(tái)。
需求1:爬取版本號(hào)為 8、11 和 17 的 Java 文本,但只顯示 “Java”,不顯示版本號(hào)。
String regex1 = "((?i)Java)(?=8|11|17)"; // 使用正向肯定預(yù)查
需求2:爬取版本號(hào)為 8、11 和 17 的 Java 文本,顯示完整的 “Java8”、“Java11” 和 “Java17”。
String regex2 = "((?i)Java)(8|11|17)"; // 匹配 Java 后面的版本號(hào)
需求3:爬取除版本號(hào)為 8、11、17 以外的 Java 文本。
String regex3 = "((?i)Java)(?!8|11|17)"; // 使用負(fù)向預(yù)查,排除指定的版本號(hào)
示例代碼:
public class RegexDemo9 {public static void main(String[] args) { String s = "Java自從95年問世以來,經(jīng)歷了很多版本,目前企業(yè)中用的最多的是Java8和Java11," + "下一個(gè)長(zhǎng)期支持版本是Java17,相信在未來不久Java17也會(huì)逐漸登上歷史舞臺(tái)";// 示例1:只匹配Java,不顯示版本號(hào)String regex1 = "((?i)Java)(?=8|11|17)";Pattern p1 = Pattern.compile(regex1);Matcher m1 = p1.matcher(s);while (m1.find()) {System.out.println(m1.group());}// 示例2:顯示Java和版本號(hào)String regex2 = "((?i)Java)(8|11|17)";Pattern p2 = Pattern.compile(regex2);Matcher m2 = p2.matcher(s);while (m2.find()) {System.out.println(m2.group());}}
}
1.12 貪婪匹配和非貪婪匹配
貪婪匹配:
在正則表達(dá)式中,默認(rèn)情況下是貪婪匹配,即在滿足匹配規(guī)則的情況下,它會(huì)盡可能多地匹配字符。
非貪婪匹配:
如果你希望正則表達(dá)式盡量少匹配字符,可以使用非貪婪匹配,即在限定范圍內(nèi),盡量少地匹配字符。
貪婪匹配和非貪婪匹配的區(qū)別在于:
- 貪婪匹配:
*
、+
等默認(rèn)是貪婪的,會(huì)盡量多匹配。 - 非貪婪匹配:在
*
、+
等后面加?
,則變?yōu)榉秦澙菲ヅ洹?/li>
示例代碼:
public class RegexDemo10 {public static void main(String[] args) {// 貪婪匹配:盡可能多地匹配String s1 = "abbbbbbbbbbbbaaaaaaaa";String regex1 = "ab+";Pattern p1 = Pattern.compile(regex1);Matcher m1 = p1.matcher(s1);while (m1.find()) {System.out.println("貪婪匹配:" + m1.group());}// 非貪婪匹配:盡可能少地匹配String regex2 = "ab+?";Pattern p2 = Pattern.compile(regex2);Matcher m2 = p2.matcher(s1);while (m2.find()) {System.out.println("非貪婪匹配:" + m2.group());}}
}
輸出結(jié)果:
貪婪匹配:abbbbbbbbbbbb
非貪婪匹配:ab
1.13 使用正則表達(dá)式切割字符串
String的split方法
Java的 String
類提供了一個(gè) split(String regex)
方法,允許根據(jù)正則表達(dá)式來拆分字符串。通過 split
,可以將匹配正則表達(dá)式的部分作為分隔符,從而把字符串切割成多個(gè)子串。
示例代碼:
public class RegexSplitDemo {public static void main(String[] args) {// 示例字符串String s = "小詩(shī)詩(shī)dqwefqwfqwfwq12312小丹丹dqwefqwfqwfwq12312小惠惠";// 使用正則表達(dá)式切割字符串,將所有非中文部分作為分隔符String[] arr = s.split("[\\w&&[^_]]+");// 遍歷并打印結(jié)果for (String str : arr) {System.out.println(str);}}
}
輸出結(jié)果:
小詩(shī)詩(shī)
小丹丹
小惠惠
1.14 使用正則表達(dá)式替換內(nèi)容
String的replaceAll方法
Java中的 replaceAll(String regex, String replacement)
方法,可以使用正則表達(dá)式找到需要替換的內(nèi)容,并將其替換為指定的字符串。這個(gè)方法會(huì)用 replacement
替換所有符合 regex
的匹配項(xiàng)。
示例代碼:
public class RegexReplaceDemo {public static void main(String[] args) {// 示例字符串String s = "小詩(shī)詩(shī)dqwefqwfqwfwq12312小丹丹dqwefqwfqwfwq12312小惠惠";// 使用正則表達(dá)式將所有非中文部分替換為"vs"String result = s.replaceAll("[\\w&&[^_]]+", "vs");// 打印替換后的字符串System.out.println(result);}
}
輸出結(jié)果:
小詩(shī)詩(shī)vs小丹丹vs小惠惠
1.15 正則表達(dá)式-分組括號(hào) ( )
分組括號(hào) ()
在正則表達(dá)式中用于將部分表達(dá)式分組,以便后續(xù)引用或者進(jìn)行邏輯處理。常見應(yīng)用包括:
- 捕獲:通過分組匹配特定內(nèi)容,并通過組號(hào)進(jìn)行提取。
- 反向引用:使用
\1
,\2
等引用之前的分組。 - 非捕獲分組:使用
(?:...)
來僅進(jìn)行分組而不進(jìn)行捕獲。
示例 1:反向引用
需求:判斷一個(gè)字符串的開始和結(jié)束字符是否一致,只考慮單個(gè)字符。
public class RegexDemo {public static void main(String[] args) {// 匹配字符串的開始和結(jié)束字符是否一致String regex = "(.).+\\1"; // 捕獲第一個(gè)字符,并在最后匹配同樣的字符System.out.println("a123a".matches(regex)); // trueSystem.out.println("b456b".matches(regex)); // trueSystem.out.println("abcba".matches(regex)); // trueSystem.out.println("abcd".matches(regex)); // false}
}
示例 2:多字符反向引用
需求:判斷字符串的開始和結(jié)束部分是否一致,并且允許多個(gè)字符。
public class RegexDemo {public static void main(String[] args) {// 匹配字符串的開始部分和結(jié)束部分是否一致,支持多字符String regex = "(.+).+\\1"; // 捕獲開始部分,并在最后匹配相同的內(nèi)容System.out.println("abc123abc".matches(regex)); // trueSystem.out.println("def456def".matches(regex)); // trueSystem.out.println("xyz789abc".matches(regex)); // false}
}
示例 3:非捕獲分組
有時(shí)我們只需要分組但不需要捕獲內(nèi)容,這時(shí)可以使用非捕獲分組 (?:...)
。這在提高效率和避免組號(hào)混淆時(shí)很有用。
public class RegexDemo {public static void main(String[] args) {// 使用非捕獲分組,只分組不捕獲String regex = "(?:abc)+"; // 匹配 "abc" 一次或多次,不捕獲System.out.println("abcabc".matches(regex)); // trueSystem.out.println("abc".matches(regex)); // trueSystem.out.println("abcd".matches(regex)); // false}
}
1.16 忽略大小寫匹配
在正則表達(dá)式中,我們可以使用 (?i)
來忽略大小寫匹配。例如,(?i)abc
將匹配 abc
、ABC
、Abc
等大小寫混合的情況。
在正則表達(dá)式中,可以使用 (?i)
來忽略大小寫的匹配。
示例:
public class RegexDemo {public static void main(String[] args) {// 忽略大小寫匹配 "abc"String regex = "(?i)abc"; // 忽略大小寫匹配 "abc"System.out.println("abc".matches(regex)); // trueSystem.out.println("ABC".matches(regex)); // trueSystem.out.println("AbC".matches(regex)); // true}
}
局部忽略大小寫:
public class RegexDemo {public static void main(String[] args) {// 匹配 "abc",只忽略中間的 "b" 大小寫String regex = "a(?i)bC"; System.out.println("aBc".matches(regex)); // trueSystem.out.println("abc".matches(regex)); // false}
}
1.17 非捕獲分組
有時(shí)候,我們希望將正則表達(dá)式的一部分進(jìn)行分組,但不希望在匹配結(jié)果中引用這個(gè)分組。我們可以使用非捕獲分組 (?:)
,這種分組不會(huì)占用分組編號(hào)。
示例:身份證號(hào)驗(yàn)證
需求:驗(yàn)證18位身份證號(hào)碼,前17位必須為數(shù)字,最后一位可以是數(shù)字或大小寫的 “X”。
public class RegexDemo {public static void main(String[] args) {// 非捕獲分組,僅用于分組不捕獲String regex = "[1-9]\\d{16}(?:\\d|X|x)";System.out.println("41080119930228457X".matches(regex)); // trueSystem.out.println("510801197609022309".matches(regex)); // trueSystem.out.println("15040119810705387x".matches(regex)); // true}
}
gex)); // true
System.out.println(“abc”.matches(regex)); // false
}
}
---## 1.17 非捕獲分組有時(shí)候,我們希望將正則表達(dá)式的一部分進(jìn)行分組,但不希望在匹配結(jié)果中引用這個(gè)分組。我們可以使用非捕獲分組 `(?:)`,這種分組不會(huì)占用分組編號(hào)。### 示例:身份證號(hào)驗(yàn)證需求:驗(yàn)證18位身份證號(hào)碼,前17位必須為數(shù)字,最后一位可以是數(shù)字或大小寫的 "X"。```java
public class RegexDemo {public static void main(String[] args) {// 非捕獲分組,僅用于分組不捕獲String regex = "[1-9]\\d{16}(?:\\d|X|x)";System.out.println("41080119930228457X".matches(regex)); // trueSystem.out.println("510801197609022309".matches(regex)); // trueSystem.out.println("15040119810705387x".matches(regex)); // true}
}