5D艺术网首页
商城
|
资讯
|
作品
|
博客
|
教程
|
论坛
登录
注册
加为好友
发短消息
来自:不正常人类研究中心
性别:先生
最后登录:2008-11-03
http://samuel.5d.cn/
我是来买馒头的~
首页
|
新闻
|
话题
|
博客
|
相册
|
艺术作品
|
社交关系
|
留言板
|
社交圈
2005/02/18 | 在Java中使用正则表达式
类别(Programme)
|
评论
(0)
|
阅读(57)
|
发表于 11:48
jdk1.4中加入了java.util.regex包提供对正则表达式的支持。而且Java.lang.String类中的replaceAll和split函数也是调用的正则表达式来实现的。
正则表达式对字符串的操作主要包括:字符串匹配,指定字符串替换,指定字符串查找和字符串分割。下面就用一个例子来说明这些操作是如何实现的:
<%@ page import="java.util.regex.*"%>
<%
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("baaaaab");
b = m.matches();
out.println(b+"<br>");
//字符串匹配,这是符合的
p = Pattern.compile("a*b");
m = p.matcher("aaaaab");
b = m.matches();
out.println(b+"<br>");
//字符串替换
p = Pattern.compile("ab");
m = p.matcher("aaaaab");
s = m.replaceAll("d");
out.println(s+"<br>");
p = Pattern.compile("a*b");
m = p.matcher("aaaaab");
s = m.replaceAll("d");
out.println(s+"<br>");
p = Pattern.compile("a*b");
m = p.matcher("caaaaab");
s = m.replaceAll("d");
out.println(s+"<br>");
//字符串查找
p = Pattern.compile("cat");
m = p.matcher("one cat two cats in the yard");
sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, "dog");
i++;
}
m.appendTail(sb);
out.println(sb.toString()+"<br>");
out.println(i+"<br>");
i=0;
p = Pattern.compile("cat");
m = p.matcher("one cat two ca tsi nthe yard");
sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, "dog");
i++;
}
m.appendTail(sb);
out.println(sb.toString()+"<br>");
out.println(i+"<br>");
p = Pattern.compile("cat");
m = p.matcher("one cat two cats in the yard");
p=m.pattern();
m = p.matcher("bacatab");
b = m.matches();
out.println(b+"<br>");
s = m.replaceAll("dog");
out.println(s+"<br>");
i=0;
p = Pattern.compile("(fds){2,}");
m = p.matcher("dsa da fdsfds aaafdsafds aaf");
sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, "dog");
i++;
}
m.appendTail(sb);
out.println(sb.toString()+"<br>");
out.println(i+"<br>");
p = Pattern.compile("cat");
m = p.matcher("one cat two cats in the yard");
sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, "<font color=\"red\">cat</font>");
}
m.appendTail(sb);
out.println(sb.toString()+"<br>");
String aa=sb.toString();
out.println(aa+"<br>");
//字符串分割
p = Pattern.compile("a+");
String[] a=p.split("caaaaaat");
for(i=0;i<a.length;i++)
{
out.println(a[i]+"<br>");
}
p = Pattern.compile("a+");
a=p.split("c aa aaaa t",0);
for(i=0;i<a.length;i++)
{
out.println(a[i]+"<br>");
}
p = Pattern.compile(" +");
a=p.split("c aa aaaa t",0);
for(i=0;i<a.length;i++)
{
out.println(a[i]+"<br>");
}
p = Pattern.compile("\\+");
a=p.split("dsafasdfdsafsda+dsagfasdfa+sdafds");
out.println(a.length+"<br>");
for(i=0;i<a.length;i++)
{
out.println(a[i]+"<br>");
}
%>
关于正则表达式的详解,可以参考
http://www.ccw.com.cn/htm/app/aprog/01_7_31_4.asp
0
评论
Comments
日志分类
首页
[50]
MyBlog
[11]
WebService
[3]
Programme
[19]
Pastime
[17]