Java程序中使用正则表达式
Java程序中使用正则表达式
-
相关类位于java.util.regex包下面
-
类Pattern:
-
正则表达式的编译表示形式
-
Pattern p = Pattern.compile(r,int); //建立正则表达式,并启用相应模式
-
-
类Matcher
-
通过解释Pattern 对character sequence执行匹配操作的引擎
-
Matcher m = p.matcher(str); //匹配str字符串
-
Demo
package regex;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo01 {
public static void main(String[] args) {
test1();
test2();
test3();
test4();
}
public static void test1(){
//在这个字符串:asfsdf23333,是否符合指定的正则表达式: w+
//表达式对象
Pattern p = Pattern.compile("\\w+");
//创建Matcher对象
Matcher m = p.matcher("asfsdf23333&&3222");
//尝试将整个字符序列与该模式匹配
//boolean b = m.matches();
//true
//System.out.println(b);
//该方法扫描输入的序列,查找与该模式匹配的下一个子序列
//boolean p2 = m.find();
//System.out.println(p2);
//boolean p3 = m.find();
//System.out.println(p3);
//boolean p4 = m.find();
//System.out.println(p4);
//打印找到的内容
//System.out.println(m.group());
//group(),group(0)匹配整个表达式的子字符串,1,2,3...表示分组
while(m.find()){
System.out.println(m.group());
}
}
//分组
public static void test2(){
//表达式对象
Pattern p = Pattern.compile("([a-z]+)([0-9]+)");
//创建Matcher对象
Matcher m = p.matcher("aaa2323**ssds4343*dsd546");
while(m.find()){
System.out.println(m.group());
System.out.println(m.group(1));
System.out.println(m.group(2));
}
}
//替换
public static void test3(){
//表达式对象
Pattern p = Pattern.compile("[0-9]");
//创建Matcher对象
Matcher m = p.matcher("aaa2323**ssds4343*dsd546");
String newStr = m.replaceAll("#");
System.out.println(newStr);
}
//分割
public static void test4(){
String str = "a23dfd34g5";
String[] arrs = str.split("\\d+");
System.out.println(Arrays.toString(arrs));
}
}
简单应用
package regex;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 网络爬虫取连接
* @author Matrix42
*
*/
public class WebSpider {
//获得url对应网页的内容
public static String getURLContent(String urlStr,String charSet){
StringBuilder sb = new StringBuilder();
try{
URL url = new URL("http://www.163.com");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(),
Charset.forName(charSet)));
String temp = "";
while((temp=reader.readLine())!=null){
sb.append(temp);
}
}catch(Exception e){
e.printStackTrace();
}
return sb.toString();
}
public static List<String> getMatcherSubstrs(String destStr,String regex) {
//System.out.println(destString);
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(destStr);
List<String> result = new ArrayList<String>();
while(m.find()){
result.add(m.group(1));
//System.out.println(m.group(1));
}
return result;
}
public static void main(String[] args) {
String destString = getURLContent("http://www.163.com","gbk");
List<String> result= getMatcherSubstrs(destString, "href=\"([\\w\\s./:#]+?)\"");
for (String string : result) {
System.out.println(string);
}
}
}