本文实例讲述了java正则表达式实现提取需要的字符并放入数组。分享给大家供大家参考,具体如下:
这里演示Java正则表达式提取需要的字符并放入数组,即ArrayList数组去重复功能。
具体代码如下:
代码如下 | 复制代码 |
packagecom.test.tool; importjava.util.ArrayList; importjava.util.HashSet; importjava.util.regex.*; publicclassMatchTest { publicstaticvoidmain(String[] args) { String regex ="[0-9]{5,12}"; String input ="QQ120282458,QQ120282458 QQ125826"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(input); ArrayList al=newArrayList(); while(m.find()) { al.add(m.group(0)); } System.out.println("去除重复值前"); for(inti=0;i { System.out.println(al.get(i).toString()); } //去除重复值 HashSet hs=newHashSet(al); al.clear(); al.addAll(hs); System.out.println("去除重复值后"); for(inti=0;i { System.out.println(al.get(i).toString()); } } } |
输出结果为:
去除重复值前 120282458 120282458 125826 去除重复值后 125826 120282458 |
改进版:弄成一个bean:
| |
代码如下 | 复制代码 |
packagecom.test.tool; importjava.util.ArrayList; importjava.util.HashSet; importjava.util.regex.*; publicclassMatchTest { privateString regex; privateString input; privateArrayList al; publicString getRegex() { returnregex; } publicvoidsetRegex(String regex) { this.regex = regex; } publicString getInput() { returninput; } publicvoidsetInput(String input) { this.input = input; } publicArrayList getAl() { returnal; } publicvoidsetAl(ArrayList al) { this.al = al; } publicMatchTest(String regex,String input) { Pattern p=Pattern.compile(regex); Matcher m=p.matcher(input); ArrayList myal=newArrayList(); while(m.find()) { myal.add(m.group()); } HashSet hs=newHashSet(myal); myal.clear(); myal.add(hs); this.setRegex(regex); this.setInput(input); this.setAl(myal); } publicMatchTest(){} publicstaticvoidmain(String[] args){ String regex1 ="[0-9]{5,12}"; String input1="QQ120282458,QQ120282458 QQ125826"; //String input1="QQ"; MatchTest mt=newMatchTest(regex1,input1); for(inti=0;i { System.out.println(mt.getAl().get(i).toString()); } } } |