現在通過例子來說明:
1、要求查找一段字符串里面相關匹配的字符串,然后根據要求奇偶大小寫替換。
1、1先從不考慮奇偶考慮
程序如下:
1
Pattern p = Pattern.compile("hello");
2
Matcher m = p.matcher("hello Hello HELLo HeLLo HelLoworld HellOWORLD dafdasfadsf");
3
4
while(m.find()){
5
System.out.println(m.group());
6
}
7
System.out.println("----------------");
8
System.out.println(m.replaceAll("HELLO"));
輸出如下:
2

3

4

5

6

7

8

hello
----------------
HELLO Hello HELLo HeLLo HelLoworld HellOWORLD dafdasfadsf
注:只有第一個hello是匹配的,所以打印出來只有一個hello
*在JDK文檔中對Pattern的描述是:A compiled representation of a regular expression.
其中complie( )方法是把里面的字符串"hello"先編譯
matcher( )方法就是把要校驗的字符串加載進來:
matcher
public Matcher matcher(CharSequence input)
- Creates a matcher that will match the given input against this pattern.
- Parameters:
input
- The character sequence to be matched- Returns:
- A new matcher for this pattern
**Matcher在JDK文檔里面描述是:
An engine that performs match operations on a character sequence
by interpreting a
Pattern
.
A matcher is created from a pattern by invoking the pattern's matcher
method. Once created, a matcher can be used to perform three different kinds of match operations:
***其中replaceAll方法是替換字符串里面符合“hello”的字符串
源碼為:
1
public String replaceAll(String replacement) {
2
reset();
3
boolean result = find();
4
if (result) {
5
StringBuffer sb = new StringBuffer();
6
do {
7
appendReplacement(sb, replacement);
8
result = find();
9
} while (result);
10
appendTail(sb);
11
return sb.toString();
12
}
13
return text.toString();
14
}
--------------------------------------------------------------------------------------
2

3

4

5

6

7

8

9

10

11

12

13

14

1、2下面對1、1中實現所有替換所有符合的字符串程序進行重構
源碼如下:
1
Pattern p = Pattern.compile("hello",Pattern.CASE_INSENSITIVE);
2
Matcher m = p.matcher("hello Hello HELLo HeLLo HelLoworld HellOWORLD dafdasfadsf");
3
StringBuffer sb= new StringBuffer();
4
int i = 0;
5
while(m.find())
6
{
7
i++;
8
if(i%2 == 0)
9
{
10
m.appendReplacement(sb, "hello");
11
}else{
12
m.appendReplacement(sb, "HELLO");
13
}
14
15
}
16
m.appendTail(sb);
17
System.out.println(sb);
控制臺輸出:
2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

HELLO hello HELLO hello HELLOworld helloWORLD dafdasfadsf
第1行中的Pattern.CASE_INSENSITIVE是忽略字母大小寫
其中第5----13行加入就奇偶判斷
appendReplacement就是把替換后的字符串放進StringBuffer的引用里面
源碼為:
1
public Matcher appendReplacement(StringBuffer sb, String replacement) {
2
3
// If no match, return error
4
if (first < 0)
5
throw new IllegalStateException("No match available");
6
7
// Process substitution string to replace group references with groups
8
int cursor = 0;
9
String s = replacement;
10
StringBuffer result = new StringBuffer();
11
12
while (cursor < replacement.length()) {
13
char nextChar = replacement.charAt(cursor);
14
if (nextChar == '\\') {
15
cursor++;
16
nextChar = replacement.charAt(cursor);
17
result.append(nextChar);
18
cursor++;
19
} else if (nextChar == '$') {
20
// Skip past $
21
cursor++;
22
23
// The first number is always a group
24
int refNum = (int)replacement.charAt(cursor) - '0';
25
if ((refNum < 0)||(refNum > 9))
26
throw new IllegalArgumentException(
27
"Illegal group reference");
28
cursor++;
29
30
// Capture the largest legal group string
31
boolean done = false;
32
while (!done) {
33
if (cursor >= replacement.length()) {
34
break;
35
}
36
int nextDigit = replacement.charAt(cursor) - '0';
37
if ((nextDigit < 0)||(nextDigit > 9)) { // not a number
38
break;
39
}
40
int newRefNum = (refNum * 10) + nextDigit;
41
if (groupCount() < newRefNum) {
42
done = true;
43
} else {
44
refNum = newRefNum;
45
cursor++;
46
}
47
}
48
49
// Append group
50
if (group(refNum) != null)
51
result.append(group(refNum));
52
} else {
53
result.append(nextChar);
54
cursor++;
55
}
56
}
57
58
// Append the intervening text
59
sb.append(getSubSequence(lastAppendPosition, first));
60
// Append the match substitution
61
sb.append(result.toString());
62
63
lastAppendPosition = last;
64
return this;
65
}

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

注:通過在java中使用正則表達式,可以很方便進行字符串校驗。
附(例子):郵件格式校驗
System.out.println("aa.a-aaa@163.com".matches("[\\w[.-]]+@[\\w[.-]]+\\.[\\w]+"));
等價于以下代碼:
Pattern pp = Pattern.compile("[\\w[.-]]+@[\\w[.-]]+\\.[\\w]+");
Matcher m =pp.matcher("aa.a-aaa@163.com");
System.out.println(m.matches());
如果符合matches里面的校驗規則,則打印出true,否則是false。
matches方法是String里面一個方法,看源碼實現
1
public boolean matches(String regex) {
2
return Pattern.matches(regex, this);
3
}

2

3

1
public static boolean matches(String regex, CharSequence input) {
2
Pattern p = Pattern.compile(regex);
3
Matcher m = p.matcher(input);
4
return m.matches();
5
}

2

3

4

5

總結:深入一些框架的底層,其中很多校驗功能都是用到正則表達式,你會發覺使用正則表達式功能很強大。
-------------------------------------------------------------------------------------------------
PS:本博客文章,如果沒有注明是有“轉”字樣,屬于本人原創。如果需要轉載,務必注明作者和文章的詳細出處地址,否則不允許轉載,多謝合作!