天天看点

Java正则表达式查找字符串

想用java的正则表达式查找字符串,发现要调好几个方法,比较python麻烦好多,于是封装了个方法,第一个参数是正则表达式,第二个参数是被查找的文本
public static List<String> regEx(String patten,String textArea) {
		String pattern = patten;
		Pattern compile = Pattern.compile(pattern);
		Matcher matcher = compile.matcher(textArea);
		List<String> targetList = new ArrayList<String>();
		while (matcher.find()) {
			String substring = textArea.substring(matcher.start(), matcher.end());
			targetList.add(substring);
		}
		return targetList;
	}
           
示例代码:
@Test
public void testRegEx() {
	String picname = "filename=\"1.0abc123.jpg\"";
	String patten = "(?<==\")\\S*\\.\\w*(?=\")";
	List<String> picNameList = RegExUitl.regEx(patten, picname);
	if (picNameList.size()>0) {
		System.out.println(picNameList.get(0)); // 1.0abc123.jpg
	}else {
		System.out.println("没有要查找的内容");
	}
	
}