匹配类代码:
package future; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Regexclass { //pattern 正则表达式,不能为空 //Sourcecode 需要正则的文本,不能为空 /*该函数功能是正则匹配出所有结果到一个String数组中*/ public static String [] GetRegResult(String pattern,String Sourcecode){ Pattern p = Pattern.compile( pattern); Matcher m = p.matcher( Sourcecode); ArrayList<String> tempList = new ArrayList<String>(); while(m.find()){ tempList.add(m.group()); } String[] res = new String[tempList.size()]; int i = 0; for(String temp : tempList){ res[i] = temp; i++; } return res; } }
主程序测试代码
package future; public class Test { public static void main(String[] args) { // TODO 自动生成的方法存根 String str = "1云2未3归4来"; String pattern = "\\d{1,}"; String [] res= Regexclass.GetRegResult(pattern, str); for (int i=0;i<res.length;i++){ System.out.println(res[i]); } } }