1、
在表達(dá)式中有特殊意義,需要添加 """ 才能匹配該字符本身的字符匯總
字符 |
說明 |
^ |
匹配輸入字符串的開始位置。要匹配 "^" 字符本身,請使用 ""^" |
$ |
匹配輸入字符串的結(jié)尾位置。要匹配 "$" 字符本身,請使用 ""$" |
( ) |
標(biāo)記一個(gè)子表達(dá)式的開始和結(jié)束位置。要匹配小括號(hào),請使用 ""(" 和 "")" |
[ ] |
用來自定義能夠匹配 '多種字符' 的表達(dá)式。要匹配中括號(hào),請使用 ""[" 和 ""]" |
{ } |
修飾匹配次數(shù)的符號(hào)。要匹配大括號(hào),請使用 ""{" 和 ""}" |
. |
匹配除了換行符("n)以外的任意一個(gè)字符。要匹配小數(shù)點(diǎn)本身,請使用 ""." |
? |
修飾匹配次數(shù)為 0 次或 1 次。要匹配 "?" 字符本身,請使用 ""?" |
+ |
修飾匹配次數(shù)為至少 1 次。要匹配 "+" 字符本身,請使用 ""+" |
* |
修飾匹配次數(shù)為 0 次或任意次。要匹配 "*" 字符本身,請使用 ""*" |
| |
左右兩邊表達(dá)式之間 "或" 關(guān)系。匹配 "|" 本身,請使用 ""|" |
比較{? + *}用法
1
public class DataMatcher {
2
public static void main(String[] args) {
3
String input = "aab ab acb ";
4
String regex = "e.+?d";
5
String regex1 = "a*b";
6
String regex2 = "a+b";
7
String regex3 = "a?b";
8
9
Pattern p = Pattern.compile(regex1);
10
Matcher m = p.matcher(input);
11
12
while(m.find()){
13
System.out.println("match: '" + m.group() + "' start: " + m.start() + " end: " + m.end());
14
}
15
}
16
}

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

regex1 result:
1
match: 'aab' start: 0 end: 3
2
match: 'ab' start: 4 end: 6
3
match: 'b' start: 9 end: 10

2

3

regex2 result
1
match: 'aab' start: 0 end: 3
2
match: 'ab' start: 4 end: 6

2

regex3 result
1
match: 'ab' start: 1 end: 3
2
match: 'ab' start: 4 end: 6
3
match: 'b' start: 9 end: 10

2

3

{.}的用法
1
String regex = "a.*?b";
2
String input = "eaab ab eb acb acsd df ad";
3

2

3

result:
1
match: 'aab' start: 1 end: 4
2
match: 'ab' start: 5 end: 7
3
match: 'acb' start: 11 end: 14

2

3

{|}的用法
1
String input = "eaab ab eb acb acsd df ad";
2
String regex = "(a.*?)(b|d)";

2

result:
1
match: 'aab' start: 1 end: 4
2
match: 'ab' start: 5 end: 7
3
match: 'acb' start: 11 end: 14
4
match: 'acsd' start: 15 end: 19
5
match: 'ad' start: 23 end: 25

2

3

4

5

{[]}用法
1
String input = "a b c da ab";
2
String regex = "[ab]";

2

result:
1
match: 'a' start: 0 end: 1
2
match: 'b' start: 2 end: 3
3
match: 'a' start: 7 end: 8
4
match: 'a' start: 9 end: 10
5
match: 'b' start: 10 end: 11

2

3

4

5
