1 练习(匹配)
2 /*
3 * 通过正则表达式,实现手机号只能是13xxx 15xxx 18xxx.
4 */
5 package bolgtest;
6 import java.io.*;
7 public class RegexTest1 {
8
9 public static void main(String[] args)throws Exception {
10 BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
11 String a = buffer.readLine();
12 String regex = "[1][358]\\d{9}";
13 System.out.println(a.matches(regex));
14 buffer.close();
15
16
17 }
18
19 }
1 练习(替换)
2 /*
3 * 把字符串“ddaghdfjjiifhdhddoooo”中的叠词替换成单个符号
4 */
5 package bolgtest;
6
7 public class RegexTest2 {
8
9 public static void main(String[] args) {
10 String str = new String("ddaghdfjjiifhdhddoooo");
11 String regex = "(.)\\1*";
12 String strcopy = str.replaceAll(regex, "$1");
13 System.out.println(strcopy);
14
15 }
16
17 }
1 练习(切割)
2 /*
3 * 已知字符串"ddaghdfjjiifhdhddoooo",按叠词切割该字符串
4 */
5
6 package bolgtest;
7
8 public class RegexTest3 {
9
10 public static void main(String[] args) {
11 String str = new String("ddaghdfjjiifhdhddoooo");
12 String regex = "(.)\\1+";
13 String[] strArray = new String[10];
14 strArray = str.split(regex);
15 for(String s : strArray){
16 System.out.println(s);
17 }
18
19
20 }
21
22 }
1 练习
2 /*
3 * 字符串"ming tian jiu yao fang jia le "通过正则表达式获取三个字母构成的单词
4 */
5
6 package bolgtest;
7
8 import java.util.regex.Matcher;
9 import java.util.regex.Pattern;
10
11 public class RegexTest4 {
12
13 public static void main(String[] args) {
14 String str = "ming tian jiu yao fang jia le";
15 String regex = "\\b[a-z]{3}\\b";
16 Pattern pattern = Pattern.compile(regex);
17 Matcher mather = pattern.matcher(str);
18 while(mather.find()){
19 System.out.println(mather.group());
20 }
21
22 }
23
24 }