一个利用正则表达式来从文本中过滤提取数据的工具类。可以用来抓取网页后过滤所需的文本。^_^
正则表达式语法规则可参考:http://blog.youkuaiyun.com/clementad/article/details/46661279
代码如下:
package com.xjj.util;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 正则表达式工具
* @author XuJijun
*
*/
public class RegexUtils {
/**
* 使用正则表达式REGEX从文本INPUT(比如html文档)中获取匹配的字符串
* @param INPUT
* @param REGEX
* @return 匹配到的所有字符串
*/
public static List<String> getContentByPattern(String INPUT, String REGEX){
List<String> resultList = new ArrayList<>();
Pattern p = Pattern.compile(REGEX); //根据正则表达式构造一个Pattern对象
Matcher m = p.matcher(INPUT); //利用patter对象为被匹配的文本构造一个Matcher对象
while(m.find()){ //如果在任何位置中发现匹配的字符串……
resultList.add(m.group()); //保存匹配到的字符串
}
return resultList;
}
/**
* 使用正则表达式REGEX从文本INPUT中获取第一个匹配的字符串
* @param INPUT
* @param REGEX
* @return
*/
public static String getFirstMatch(String INPUT, String REGEX){
return getContentByPattern(INPUT, REGEX).get(0);
}
/**
* 根据正则表达式REGEX,把INPUT中所有被匹配到的字符串替换成REPLACE
* @param INPUT
* @param REGEX
* @param REPLACE
*/
public static String replaceContentByPattern(String INPUT, String REGEX, String REPLACE){
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(INPUT);
return m.replaceAll(REPLACE);
}
/**
* 从INPUT中找到第一串数字
* @param INPUT
* @return
*/
public static String findFirstNumber(String INPUT){
Pattern p=Pattern.compile("\\d+");
Matcher m=p.matcher(INPUT);
if(m.find()){
return m.group();
}else {
return null;
}
}
}
用例1:
@Test
public void getContentByPattern(){
String INPUT = "我是123,不是678。";
String REGEX = "\\d+";
List<String> result = RegexUtils.getContentByPattern(INPUT, REGEX);
System.out.println(result);
}
结果:
[123, 678]
用例2:
@Test
public void getFirstMatch(){
String INPUT = "我是123,不是678。";
String REGEX = "不是\\d+";
String result = RegexUtils.getFirstMatch(INPUT, REGEX);
System.out.println(result);
}
结果:
不是678
用例3:
@Test
public void replaceContentByPattern(){
String INPUT = "我是123,不是678。";
String REGEX = "123";
String result = RegexUtils.replaceContentByPattern(INPUT, REGEX, "100");
System.out.println(result);
}
结果:
我是100,不是678。
用例4:
@Test
public void findFirstNumber(){
String INPUT = "我是123,不是678。";
String result = RegexUtils.findFirstNumber(INPUT);
System.out.println(result);
}
结果:
123
(原创文章,转载请注明转自Clement-Xu的博客 )