-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsection.java.util.regex.xml
More file actions
119 lines (98 loc) · 2.84 KB
/
section.java.util.regex.xml
File metadata and controls
119 lines (98 loc) · 2.84 KB
1
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
<?xml version="1.0" encoding="UTF-8"?>
<chapter id="java.util.regex">
<title>正则表达式</title>
<programlisting>
<![CDATA[
package cn.netkiller;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("www|netkiller");
Matcher matcher = pattern.matcher("http://www.netkiller.cn/linux/index.html");
if (matcher.find()) {
System.out.println(matcher.group());
}
}
}
]]>
</programlisting>
<section>
<title>正则查找</title>
<para></para>
<programlisting>
<![CDATA[
Matcher matcher = Pattern.compile("播放|暂停|停止").matcher("当前暂停音乐");
if(matcher.find()){
System.out.println(matcher.group(0));
}
if(Pattern.compile("播放|暂停|停止").matcher("当前停音乐").find()){
System.out.println("查找到");
}
]]>
</programlisting>
</section>
<section>
<title>正则替换</title>
<programlisting>
<![CDATA[
package cn.netkiller;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("www|netkiller");
Matcher matcher = pattern.matcher("https://www.netkiller.cn/linux/index.html");
if (matcher.find()) {
String s = matcher.replaceFirst("api"); //替换后的字符串
System.out.println(s);
}
}
}
]]>
</programlisting>
<programlisting>
<![CDATA[
package cn.netkiller;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("www|netkiller");
Matcher matcher = pattern.matcher("https://www.netkiller.cn/linux/index.html");
if (matcher.find()) {
String s = matcher.replaceAll("test"); //替换后的字符串
System.out.println(s);
// 输出结果:https://test.test.cn/linux/index.html
}
}
}
]]>
</programlisting>
<para></para>
<programlisting>
<![CDATA[
"aab".replaceAll("a{1}", "x"); //xxb
"aba".replaceAll("a{1}", "x"); //xbx
"abaaabaaaba".replaceAll("a{2}", "x"); //abxabxaba
"abaabaaaaba".replaceAll("a{2}", "x"); //abxbxxba
]]>
</programlisting>
</section>
<section>
<title>字符串分割</title>
<programlisting>
<![CDATA[
String input = "苹果!!香蕉!!鸭梨!!橘子";
System.out.println(Arrays.toString(Pattern.compile("!!").split(input)));
System.out.println(Arrays.toString(Pattern.compile("!!").split(input, 3)));
]]>
</programlisting>
<screen>
<![CDATA[
[苹果, 香蕉, 鸭梨, 橘子]
[苹果, 香蕉, 鸭梨!!橘子]
]]>
</screen>
</section>
</chapter>