在Java中使用正则表达式:
Pattern p = null; //正则表达式
Matcher m = null; //操作的字符串
boolean b;
String s = null;
StringBuffer sb = null;
int i = 0;
//判断字符串是否匹配
p = Pattern.compile("a*b");
m = p.matcher("baaaab");
b = m.matches();//不匹配
//字符串替换
p = Pattern.compile("ab");
m = p.matcher("aaaaaab");
s = m.replaceAll("d");
out.println(s);
p = Pattern.compile("a*b");
m = p.matcher("aaaaab");
s = m.replaceAll("d");
out.println(s);
//字符串查找
p = Pattern.compile("cat");
m = p.matcher("one cat two cats");
sb = new StringBuffer();
while(m.find()){
m.appendReplacement(sb,"dog");
i++;
}
m.appendTail(sb);
out.println(sb);
//字符串分割
p = Pattern.compile("a+");
String []a = p.split("caaaaat");
for(i=0;i<a.length;a++)
{
out.println(a[i]);
}