title: 初識正則表達式
date: 2019-02-23 22:09:32
tags:
- JavaSE
categories:
- JavaSE
正則表達式概述及基本使用
指一個用來描述或者匹配一系列符合某個句法規則的字符串的單個字符串。其實就是一種規則。有自己特殊的應用。
常見規則
規則字符在java.util.regex
包下的Pattern
類中。
A:字符
x 字符 x。舉例:'a'表示字符a
\\ 反斜線字符。
\n 新行(換行)符 ('\u000A')
\r 回車符 ('\u000D')
B:字符類
[abc] a、b 或 c(簡單類)
[^abc] 任何字符,除了 a、b 或 c(否定)
[a-zA-Z] a到 z 或 A到 Z,兩頭的字母包括在內(範圍)
[0-9] 0到9的字符都包括
C:預定義字符類
. 任何字符。我的就是.字符本身,怎麼表示呢? \.
\d 數字:[0-9]
\w 單詞字符:[a-zA-Z_0-9]
在正則表達式裏面組成單詞的東西必須有這些東西組成
D:邊界匹配器
^ 行的開頭
$ 行的結尾
\b 單詞邊界
就是不是單詞字符的地方。
舉例:hello world?haha;xixi
E:Greedy 數量詞
X? X,一次或一次也沒有
X* X,零次或多次
X+ X,一次或多次
X{n} X,恰好 n 次
X{n,} X,至少 n 次
X{n,m} X,至少 n 次,但是不超過 m 次
常用功能
A:判斷功能
String類的public boolean matches(String regex):判斷此字符串是否匹配給定的正則表達式
B:分割功能
String類的public String[] split(String regex):根據給定正則表達式的匹配拆分此字符串。
C:替換功能
String類的public String replaceAll(String regex,String replacement):使用給定的 replacement 替換此字符串所有匹配給定的正則表達式的子字符串。
D:獲取功能
Pattern和Matcher
Pattern p = Pattern.compile("a*b");
Matcher m = p.matcher("aaaaab");
find():查找存不存在
group():獲取剛纔查找過的數據
獲取功能的典型調用如下:
// 典型的調用如下
// 模式和匹配器的典型調用順序
// 把正則表達式編譯成模式對象
Pattern p = Pattern.compile("a*b");
// 通過模式對象得到匹配器對象,這個時候需要的是被匹配的字符串
Matcher m = p.matcher("aaaaab");
// 調用匹配器對象的功能
boolean b = m.matches();
System.out.println(b);
舉個栗子:
/*
* 獲取功能:
* 獲取下面這個字符串中由三個字符組成的單詞
* da jia ting wo shuo,jin tian yao xia yu,bu shang wan zi xi,gao xing bu?
*/
public class RegexDemo2 {
public static void main(String[] args) {
// 定義字符串
String s = "da jia ting wo shuo,jin tian yao xia yu,bu shang wan zi xi,gao xing bu?";
// 規則
String regex = "\\b\\w{3}\\b";
// 把規則編譯成模式對象
Pattern p = Pattern.compile(regex);
// 通過模式對象得到匹配器對象
Matcher m = p.matcher(s);
while (m.find()) {
System.out.println(m.group());
}
}
}