您的位置:首页 > 编程语言 > Java开发

java 正则表达式用法(2)

2013-12-05 16:16 253 查看
查找一段短文中的单词、汉字、数字的个数:

import java.util.*;
import java.util.regex.*;

public class RegexDemo2 {

public static ArrayList<String> getMatchList(String reg, String input){
ArrayList<String> list = new ArrayList<String>();
Pattern p = Pattern.compile(reg, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(input);
while(m.find()){
list.add(m.group());
}
return list;
}
public static void printList(ArrayList<String> list, String message){
for(String s : list)
System.out.println(s);
System.out.println("共有" + message + "个数:" + list.size());
}

public static void main(String arg[]) {

String input = "Do one thing at a time, and do well. 一次只做一件事,并做到最好。x1,1y,2013,2014";
String regEng = "\\b[a-z]+\\b";
String regCn = "[\u4e00-\u9fa5]";
String regNum = "\\b\\d+\\b";
int eng = 0, cn = 0, num = 0;

ArrayList<String> listEng = getMatchList(regEng, input);
printList(listEng, "单词");

ArrayList<String> listCn = getMatchList(regCn, input);
printList(listCn, "汉字");

ArrayList<String> listNum = getMatchList(regNum, input);
printList(listNum, "数字");

}
}

/*
Do
one
thing
at
a
time
and
do
well
共有单词个数:9
一
次
只
做
一
件
事
并
做
到
最
好
共有汉字个数:12
2013
2014
共有数字个数:2
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  正则表达式