定義:正則表達(dá)式使用單個(gè)字符串來(lái)描述、匹配一系列匹配某個(gè)句法規(guī)則的字符串。正則表達(dá)式使用單個(gè)字符串來(lái)描述、匹配一系列匹配某個(gè)句法規(guī)則的字符串。
Example : 匹配 github.com 的url
public String githubUrl = "https://github.com/BJChaney/BJChaney.github.io?1=1&2=2";
public String githubRegex = "(https?://)?github.com(/[\\w._]+)*\\??([\\w_]+=[\\w._]+&?)*";
基本概念
1. 字符表示
| 字符 | 含義 |
|---|---|
| . | 任意字符 |
| [abc] | a,b,c中其中一個(gè) |
| [^abc] | 非a,b,c的字符 |
| [a-z] | 從a到z的任意字符 |
| [a-z&&[a-c]] | a到c的任意字符(兩集合交集) |
| \s | 空白字符(空格,回車(\r),換行(\n),tab(\t),換頁(yè)(/f)) |
| \S | 非空白字符 |
| \d | 數(shù)字[0-9] |
| \D | 非數(shù)字 |
| \w | 詞字符[a-zA-Z0-9] |
| \W | 非詞字符 |
2. 頻率表示符
| 字符 | 含義 |
|---|---|
| * | 0次或多次 |
| ? | 1次或0次 |
| + | 1次或多次 |
| X{n} | 剛好n次 |
| X{n,} | 最少n次 |
| X{n,m} | 大于n次,小于m次 |
3. 邏輯操作
| 邏輯操作符 | 含義 | 例子 | |
|---|---|---|---|
| XY | Y在X后面 | abc | 邏輯順序abc,匹配一個(gè)為abc的字符串 |
| X丨Y | X或Y | abc丨def | 匹配一個(gè)abc或者一個(gè)def字符串 |
| (X) | 組 | (abc) | 可以匹配abc組,如(abc)+可以匹配abc,abcabc,abcabcabc... |
例子解析
首先分析例子,因?yàn)槭瞧ヅ?a target="_blank" rel="nofollow">github.com,所以github.com是必須存在的,http:// 請(qǐng)求頭可能存在,也可能不存在,后面的路徑和請(qǐng)求參數(shù)都是可能不存在的
-
請(qǐng)求頭表示演變
源:https://
-> https?:// 可能不是https請(qǐng)求頭
-> (https?://)? 可能整組 https:// 都不存在,存在只存在一次
-
路徑演變
源:/BJChaney/BJChaney.github.io
-> /[\w._]+ 都是/XXX的結(jié)構(gòu) 并且/之后至少有1個(gè)字符,路徑中還可能包含 . _等符號(hào)
-> (/[\w._]+)* 路徑整體是可以不存在或者存在多次的
-
參數(shù)列表演變
源:?1=1&2=2
-> \?? 參數(shù)列表如果存在,前邊必須有一個(gè)?,因?yàn)椋渴翘厥夥?hào),所以要轉(zhuǎn)義一下寫(xiě)成\?
-> [\w_]+=[\w._]+&? 參數(shù)格式為xxx=xxx,等號(hào)兩邊必須有一個(gè)字符,多個(gè)參數(shù)間可能存在&符號(hào)
-> ([\w_]+=[\w._]+&?)* 可能存在許多參數(shù)
->組合 \??([\w_]+=[\w._]+&?)*
最終組合成完整正則:(https?://)?github.com(/[\w.]+)*\??([\w]+=[\w._]+&?)*
取值
正則取值,主要是通過(guò)組()來(lái)取
組:使用括號(hào)劃分的正則表達(dá)式,默認(rèn)根據(jù)組的編號(hào)來(lái)引用組,組0表示整個(gè)表達(dá)式,組1表示第一個(gè)被括號(hào)括起的組,依此類推
Example : A(B(C))D
其中,組0為ABCD,組1為BC,組2為C
組默認(rèn)是自增方式來(lái)編號(hào)的,可以利用自定義組名去取其中某段內(nèi)容,格式:(?<組名>)
Demo:取出并打印url的參數(shù)列表
正則中添加 (?<params>)
/**
*
* @author BJChaney
*/
public class RegExpTest {
public static void main(String[] args) {
String githubUrl = "https://github.com/BJChaney/BJChaney.github.io?1=1&2=2";
String githubRegex = "(https?://)?github.com(/[\\w._]+)*\\??(?<params>([\\w_]+=[\\w._]+&?)*)";
System.out.println("match ? " + githubUrl.matches(githubRegex));
Pattern pattern = Pattern.compile(githubRegex);
Matcher matcher = pattern.matcher(githubUrl);
if (matcher.find()) {
String paramStr = matcher.group("params");
System.out.println("params : " + paramStr);
System.out.println("paramsCount : " + matcher.groupCount());
for(int i = 0 ; i <= matcher.groupCount() ; i ++){
System.out.println("group : " + i +" content : " + matcher.group(i) );
}
pattern = Pattern.compile("&");
String[] params = pattern.split(paramStr);
for (String param : params) {
String key = param.split("=")[0];
String value = param.split("=")[1];
System.out.println("key = " + key + " value = " + value);
}
}
}
}