微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

正则表达式工具类

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


正则表达式语法规则可参考: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的博客

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐