一、什麼是正則表達式
正則表達式是一種描述字元串模式的工具,它可以在字元串中匹配或查找一種特定的模式。Java中提供了對正則表達式的支持,使用Pattern和Matcher兩個類對字元串進行匹配。
二、Java正則表達式的語法
Java正則表達式包括字面量和特殊字元兩種元素。字面量就是匹配自身的字元,而特殊字元用來描述其他字元的特殊規律。
Java正則表達式的基本語法如下表所示:
| 字元 | 描述 |
| —- | —- |
| . | 匹配任意單個字元 |
| \d | 匹配數字 |
| \D | 匹配非數字 |
| \w | 匹配字母、數字、下劃線和漢字 |
| \W | 匹配非字母、數字、下劃線和漢字 |
| \s | 匹配任意空白字元 |
| \S | 匹配任意非空白字元 |
| ^ | 匹配字元串的開始部分 |
| $ | 匹配字元串的結束部分 |
| * | 匹配0次或多次 |
| + | 匹配1次或多次 |
| ? | 匹配0次或1次 |
| {n} | 匹配n次 |
| {n,} | 匹配至少n次 |
| {n,m} | 匹配n到m次 |
三、使用Java正則表達式匹配數字
如果要在字元串中找到一個或多個數字,可以使用\d或[0-9]來匹配數字。如下代碼示例:
import java.util.regex.Matcher; import java.util.regex.Pattern; public class NumberMatcher { public static void main(String[] args) { String str = "The price of the apple is 3.14 dollars, and the price of the orange is 2.68 dollars"; String regex = "\\d+(\\.\\d+)?"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(str); while (matcher.find()) { System.out.println(matcher.group()); } } }
運行結果:
3.14 2.68
四、使用Java正則表達式替換數字
除了匹配數字,還可以使用正則表達式的替換功能來將字元串中的數字替換成其它內容,如下代碼示例:
import java.util.regex.Matcher; import java.util.regex.Pattern; public class NumberReplacer { public static void main(String[] args) { String str = "The price of the apple is 3.14 dollars, and the price of the orange is 2.68 dollars"; String regex = "\\d+(\\.\\d+)?"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(str); String newStr = matcher.replaceAll("10"); System.out.println(newStr); } }
運行結果:
The price of the apple is 10 dollars, and the price of the orange is 10 dollars
五、常用的Java正則表達式
除了匹配數字之外,Java正則表達式還可以用來匹配郵箱、電話號碼、身份證號碼等特定的字元串模式。以下是幾個常用的正則表達式示例:
| 字元串模式 | 正則表達式 |
| —- | —- |
| 郵箱 | [A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6} |
| 手機號碼 | 1[3-9]\\d{9} |
| 固定電話號碼 | ((\\d{3,4}-{0,1}){0,1}\\d{7,8})|(\\d{3,4}-{0,1}\\d{3,4}-{0,1}\\d{3,4}) |
| 身份證號碼 | \\d{15}(\\d{2}[0-9xX])? |
六、注意事項
在使用Java正則表達式的時候,要注意字元轉義的問題,因為有些字元在Java中是有特殊含義的,例如”\d”表示數字,而不是單純的”d”。因此在寫正則表達式時,一定要根據需要進行轉義。
七、總結
使用Java正則表達式可以方便地匹配字元串中的特定模式,例如數字、郵箱、電話號碼等。在使用時需要注意正則表達式的語法和字元轉義問題,建議多做練習,以便熟練地掌握Java正則表達式的使用。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/193548.html