1.校验文本内容

在 Java 中,正则相关的类在 java.util.regex 中,其中最常用的是 Pattern 和 Matcher, Pattern 是正则表达式对象,Matcher是匹配到的结果对象,Pattern 和 字符串对象关联,可以得到一个 Matcher。下面是 Java 中匹配的示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Main {
public static void main(String[] args) {
//方法1,可以不加 A 和 z
System.out.println(Pattern.matches("d{4}-d{2}-d{2}", "2020-06-01")); // true

//方法2,可以不加 A 和 z
System.out.println("2020-06-01".matches("d{4}-d{2}-d{2}")); // true

//方法3,必须加上 A 和 z
Pattern pattern = Pattern.compile("Ad{4}-d{2}-d{2}z");
System.out.println(pattern.matcher("2020-06-01").find()); // true
}
}

2.提取文本内容

内容提取,就是从大段的文本中抽取出我们关心的内容。比较常见的例子是网页爬虫,或者说从页面上提取邮箱、抓取需要的内容等。如果要抓取的是某一个网站,页面样式是一样的,要提取的内容都在同一个位置,可以使用 xpathjquery选择器 等方式,否则就只能使用正则来做了。

在 Java 中,可以使用 Matcher 的 find 方法来获取查找到的内容,就像下面这样:

1
2
3
4
5
6
7
8
9
10
11
12
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("d{4}-d{2}");
Matcher match = pattern.matcher("2020-06 2020-07");
while (match.find()) {
System.out.println(match.group());
}
}
}

3.替换文本内容

在 Java 中,一般是使用 replaceAll 方法进行替换,一次性替换所有的匹配到的文本。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Main {
public static void main(String[] args) {
//方法1,输出 2020年02月20日 2020年05月21日
System.out.println("02-20-2020 05-21-2020".replaceAll("(d{2})-(d{2})-(d{4})", "$3年$1月$2日"));

//方法2,输出 2020年02月20日 2020年05月21日
final Pattern pattern = Pattern.compile("(d{2})-(d{2})-(d{4})");
Matcher match = pattern.matcher("02-20-2020 05-21-2020");
System.out.println(match.replaceAll("$3年$1月$2日"));
}
}

4.切割文本内容

1
2
3
4
5
6
7
8
9
10
11
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("W+");
for(String s : pattern.split("apple, pear! orange; tea")) {
System.out.println(s);
}
}
}

很多网页为了防止爬虫,喜欢把邮箱里面的 @ 符号替换成 # 符号,你可以写一个正则,兼容一下这种情况么?

1
2
例如网页的底部可能是这样的:
联系邮箱:xxx#163.com (请把#换成@)