正则表达式工具类
2015-06-27 15:20
344 查看
一个利用正则表达式来从文本中过滤提取数据的工具类。可以用来抓取网页后过滤所需的文本。^_^
正则表达式语法规则可参考:/article/2598083.html
代码如下:
相关的测试用例和结果:
用例1:
结果:
用例2:
结果:
用例3:
结果:
用例4:
结果:
(原创文章,转载请注明转自Clement-Xu的博客)
正则表达式语法规则可参考:/article/2598083.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---textarea初始化时就有个table空格以及tab键操作无效
- 秋叶PPT-三分钟教程
- oracle删除表中的重复数据
- MySQL基础笔记(一) SQL简介+数据类型
- MySQL基础笔记(一) SQL简介+数据类型
- ZigBee终端入网方式深入分析
- shell 水平测试
- ZOJ Problem Set - 1006 Do the Untwist
- 最短路(最短路径)
- 递归与递推实现斐波那契数列算法
- 小小知识
- AngularJS中的模块(module)
- 简单的XSS攻击
- bash shell学习-正则表达式基础 (笔记)
- LINUX环境并发服务器的三种实现模型
- 微信 oauth授权 获取用户的信息
- 设计模式之Composite模式(笔记)
- cocos2d-x3.6 连连看连通画线
- 求出最长非降子序列的长度--LIS:longest increasing subsequence
- WebSocket 一场Web 通讯革命悄然来临——Node.js摸石头系列之五