java正则表达式匹配字符串字母,数字,空格和其他字符出现次数
2012-02-09 10:44 xiangtongpeng 阅读(2385) 评论(1) 编辑 收藏 举报package com.xtp.str;
import java.util.regex.*;
public class RegexCountString{
public static void main(String[] args) {
String s = "6sabcss sfsfs33";
Pattern p = Pattern.compile("[a-z|A-Z]");
Matcher m = p.matcher(s);
long last = System.nanoTime() ;
int i = 0;
//字母
while (m.find()) {
i++;
}
System.out.println("字符串中字母出现的次数为:"+i);
//数字
p = Pattern.compile("[0-9]");
m.usePattern(p);
m.reset();//每次数restet不知会不会很慢
i = 0;
while (m.find()) {
i++;
}
System.out.println("字符串中数字出现的次数为:"+i);
//空格
p = Pattern.compile(" ");
m.usePattern(p);
m.reset();
i = 0;
while (m.find()) {
i++;
}
System.out.println("字符串中空格出现的次数为:"+i);
//去掉a|b|3
p = Pattern.compile("[a|b|3]");
m.reset();
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, "");
}
System.out.println("字符串去掉 a|b|3 之后变为:"+sb);
long now = System.nanoTime();
System.out.println("统计所用的时间总长为:"+(now - last)+"毫秒");//统计所耗费时间
}
}