如果不记得,可以去API文档搜索Pattern
public boolean matches(String regex)
//判断是否匹配正则表达式,匹配返回true,不匹配返回false。
| 方法名 | 说明 |
|---|---|
| public String replaceAll(String regex,String newStr) | 按照正则表达式匹配的内容进行替换 |
| public String[] split(String regex) | 按照正则表达式匹配的内容进行分割字符串,返回一个字符串数组 |
String names = "孙悟空fiowhg23435猪八戒fjoiw234352白龙马";
String[] s = names.split("\\w+");
for(int i=0;i<s.length;i++){
System.out.println(s[i]);
/*
输出:
孙悟空
猪八戒
白龙马
*/
}
String name2 = names.replaceAll("\\w+"," "); //用两个空格代替要替换的内容,组成新的字符串
System.out.println(name2); //孙悟空 猪八戒 白龙马
package com.lipn.regulardemo;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Crawling {
public static void main(String[] args) {
String rs = "来黑马程序员学习Java,联系邮箱itheima@itcast.cn,电话18762832633,0203232323," +
"邮箱bozai@itcast.cn,400-100-3232,4001003232";
/*
需求:
从上面的内容中爬取出电话号码和邮箱。
*/
//1.定义爬取规则,字符串形式
String regex = "1[3-9]\\d{9}|\\w{1,30}@[a-zA-Z0-9]{2,20}(\\.[a-zA-Z0-9]{2,20}){1,2}|" +
"400-?\\d{3,9}-?\\d{3,9}";
//2.把这个爬取规则编译成匹配对象
Pattern pattern = Pattern.compile(regex);
//3.得到一个内容匹配器对象
Matcher matcher = pattern.matcher(rs);
//4.开始找了
while(matcher.find()){
String rs1 = matcher.group();
System.out.println(rs1);
}
}
}