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

在Java中使用正则表达式

2007-04-26 10:45 309 查看
在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]);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: