正则表达式工具类

一个利用正则表达式来从文本中过滤提取数据的工具类。可以用来抓取网页后过滤所需的文本。^_^


正则表达式语法规则可参考:http://www.jb51.cc/article/p-caeljvvv-gw.html


代码如下:

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的博客

相关文章

正则替换html代码中img标签的src值在开发富文本信息在移动端...
正则表达式
AWK是一种处理文本文件的语言,是一个强大的文件分析工具。它...
正则表达式是特殊的字符序列,利用事先定义好的特定字符以及...
Python界一名小学生,热心分享编程学习。
收集整理每周优质开发者内容,包括、、等方面。每周五定期发...