方法名:
public String replaceAll(String regex,String newStr):按照正则表达式匹配的内容进行替换
package com.bingyi.regex;
public class StringRegexMethod {
public static void main(String[] args) {
String s = "先帝1创业2未半而中道3崩殂4,今5天下三分6,益州疲弊7,此8诚危急存亡之秋也。然9侍卫之臣不懈于内,忠志之士忘身10于外者,盖追先帝之殊遇11,欲报之于陛下也。诚宜12开张圣听13,以光14先帝遗德,恢弘15志士之气,不宜妄自菲薄16,引喻失义17,以塞忠谏之路也18。";
s = s.replaceAll("\\d", "");
System.out.println(s);
}
}
public String[] split(String regex):按照正则表达式匹配的内容进行分割字符串,返回一个字符串数组
使用正则表达式爬取信息
1.定义爬取正则
2.将正则表达式封装为一个Pattern对象
3.获取匹配器对象
4.通过匹配器,从内容中爬取信息
package com.bingyi.regex;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PatternTest {
public static void main(String[] args) {
String data = "qwertyui" +
"电话:1234567" +
"邮箱:erty@45678.cn" +
"邮箱:34560000@234.com" +
"座机电话:010234578" +
"热线电话:400-356-6543,400-764-23654";
String regex = "[a-z]|[a-z]{1,4}[@]{6,11}.[cn]+[400]";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(data);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}