- 匹配: 使用 Srting 類中的 matches 方法。
- 切割: 使用 String 類中的 split 方法。 注意: 組 -> (pattern) 匹配 pattern 並捕獲該匹配的子表達式,可以使用 $ 加數字匹配組的排序。
- 替換: 使用 String 類中的 replaceAll 方法。
- 獲取:
- 將正則規則進行對象的封裝。
- 通過正則對象的 matcher 方法將字符串相關聯。獲取要對字符串操作的匹配器對象 Matcher。
- 通過 Matcher 匹配器對象的方法對字符串進行操作。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexDemo2 {
public static void main(String[] args) {
functionDemo_1();
functionDemo_2();
functionDemo_3();
functionDemo_4();
}
// 匹配
public static void functionDemo_1() {
// 匹配手機號碼是否正確
String tel = "18550403566";
String regex = "1[358]\\d{9}";
boolean b = tel.matches(regex);
System.out.println("tel @ " + b);
}
// 切割
public static void functionDemo_2() {
String str = "Jack Vivian Mike";
String[] names = str.split("\\s+");
for (String name : names) {
System.out.println(name);
}
String str_1 = "jackmmmmvivianttttmike";
String[] names_1 = str_1.split("(.)\\1+");// 任意字符出現一次以上則匹配
for (String name : names_1) {
System.out.println(name);
}
}
// 替換
public static void functionDemo_3() {
String str = "jackmmmmvivianttttmike";
str = str.replaceAll("(.)\\1+", "#");// 任意字符且連續出現一次以上及匹配並替換為 # 號
System.out.println(str);
String tel = "18520308566";
tel = tel.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
System.out.println("tel @ " + tel);
}
// 獲取
public static void functionDemo_4() {
String str = "hello world, this is jack";
System.out.println(str);
String regex = "\\b[a-z]{4}\\b";// \b -> 匹配字邊界
// 1. 將正則封裝成對象
Pattern p = Pattern.compile(regex);
// 2. 通過正則對象獲取匹配器對象
Matcher m = p.matcher(str);
// 3. 使用 Matcher 對象的方法對字符串進行操作
// 既然要獲取三個字母組成的單詞
// 進行查找 -> find();
while (m.find()) {
System.out.println(m.group());// 獲取匹配的子序列
System.out.println(m.start() + " @ " + m.end());//匹配的子序列所在位置
}
}
}
打印結果
//functionDemo_1()
tel @ true
//functionDemo_2()
//切割空白處
Jack
Vivian
Mike
//切割疊字處
Jack
Vivian
Mike
//functionDemo_3()
//將疊字處替換為指定符號
jack#vivian#mike
//將指定處替換為指定符號
tel @ 185****8566
//functionDemo_4()
hello world, this is jack
this
13 @ 17
jack
21 @ 25