//ccc.htm\'>ccc";
Patternpattern=Ppile(patternString,Pattern.CASE_INSENSITIVE);
Matchermatcher=pattern.matcher(text);
StringBufferbuffer=newStringBuffer();
while(matcher.find()){
//整个捕获,相当于goup(0)
buffer.append("获捕到"+matcher.group());
//捕获中的一部分(第2对圆括号对应的,即是网址)
buffer.append("其中网址为"+matcher.group
(2));
buffer.append("\r\n");
}
System.out.println(buffer.toString());
}
}
2.5更多正则表达式的例子
参考:
(1)匹配美国的社会安全号码
假设我们要在文本文件中搜索美国的社会安全号码。
这个号码的格式是123-12-1234。
用来匹配它的正则表达式如图1所示。
在正则表达式中,连字符(“-”)有着特殊的意义,它表示一个范围,比如从0到9。
因此,匹配社会安全号码中的连字符号时,它的前面要加上一个转义字符“\”。
图1匹配所有123-12-1234形式的社会安全号码
【注意:
但在Java中连字符-不需要转义符\】
在Java中匹配的模式写为:
Stringpattern1="[0-9]{3}-[0-9]{2}-[0-9]d{4}";
//或通过预定义的字符\d来简化,但需要加转义符\,所以是\\d
Stringpattern1="\\d{3}-\\d{2}-\\d{4}";
假设进行搜索的时候,你希望连字符号可以出现,也可以不出现即,999-99-9999和999999999都属于正确的格式。
这时,你可以在连字符号后面加上“?
”数量限定符号,如图2所示:
Stringpattern2="[0-9]{3}-?
[0-9]{2}-?
[0-9]d{4}";
Stringpattern2="\\d{3}-?
\\d{2}-?
\\d{4}";
(2)匹配上海的汽车牌照号码
上海汽车牌照的一种格式是沪+A-Z.五个字符,如沪A.25F63,沪B.88888等。
在Java中匹配的模式写为:
Stringpattern="沪[A-Z]\\.\\w{5}";
(3)将字符串中的生日信息中提取出年、月、日的信息
假设要从格式为“June26,1951”的生日日期中提取出年月日信息
在Java中匹配的模式写为:
Stringpattern="([a-z]+)\\s*([0-9]{1,2}),\\s*([0-9]{4})";
importjava.util.regex.*;
publicclassRegexBirthday{
publicstaticvoidmain(String[]args){
StringpatternString="([a-z]+)\\s*([0-9]{1,2}),\\s*([0-9]{4})";
Stringtext="MileswasbornonJune2,1978inNingbo";
Patternpattern=Ppile(patternString,Pattern.CASE_INSENSITIVE);
Matchermatcher=pattern.matcher(text);
//StringBufferbuffer=newStringBuffer();
Stringyear=null;
Stringmonth=null;
Stringday=null;
while(matcher.find()){
month=matcher.group
(1);
day=matcher.group
(2);
year=matcher.group(3);
}
System.out.println("Milesbirthdayis"+year+""+month+""+day);
}
}
程序输出:
Milesbirthdayis1978June2
(4)匹配HTML
分析HTML页面内FONT标记的所有属性。
HTML页面内典型的FONT标记如下所示:
程序需要输出如下键值对:
face=Arial,Serif
size=+2
color=red
第1步提取出尖括号内的内容:
第2步利用group,将属性分割成键值对
3.正则表达式的综合应用
3.1简单的网络爬虫
【源代码】
import.URL;
importjava.io.*;
importjava.util.*;
importjava.util.concurrent.*;
importjava.util.regex.*;
importjava.nio.charset.*;
classURLCrawler
{
publicstaticvoidmain(String[]args)throwsException{
//并发队列
finalConcurrentLinkedQueueurls=newConcurrentLinkedQueue<>();
urls.add("");
intcnt=0;
while(!
urls.isEmpty()){
finalStringurl=urls.poll();
System.out.println(url);
//启动匿名线程
newThread(){
publicvoidrun(){
try{
Stringcontent=download(newURL(url),"gb2312");//下载网页内容ListmoreUrl=parse(content);//解析网址
urls.addAll(moreUrl);
}catch(Exceptionex){
ex.printStackTrace();
}
}
}.start();
if(cnt++>10)break;//当爬到的网址内容超过10个,停止
try{
Thread.sleep(4000);
}
catch(InterruptedExceptionex){
}
}
}
staticListparse(Stringtext){
StringpatternString=
"\\s*href\\s*=\\s*(\"([^\"]*\")|(\'[^\']*\')|([^\'\">\\s]+))\\s*";
Patternpattern=Ppile(patternString,Pattern.CASE_INSENSITIVE);
Matchermatcher=pattern.matcher(text);
Listlist=newArrayList<>();
while(matcher.find()){
Stringhref=matcher.group
(1);
href=href.replaceAll("\'","").replaceAll("\"","");
if(href.startsWith("http:
"))
list.add(href);
}
returnlist;
}
//下载网页内容
staticStringdownload(URLurl,Stringcharset)throwsException{
try(InputStreaminput=url.openStream();
ByteArrayOutputStreamoutput=newByteArrayOutputStream()){
byte[]data=newbyte[1024];
intlength;
while((length=input.read(data))!
=-1){
output.write(data,0,length);
}
byte[]content=output.toByteArray();
returnnewString(content,Charset.forName(charset));
}
}
}
3.2网站日志分析
ApacheHTTP日志服务器的标准日志:
127.0.0.1-frank[10/Oct/2000:
13:
55:
36-0700]"GET/apache_pb.gifHTTP/1.0"2002326
如何提取IP和访问日期信息?
StringpatternIP="\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}";
StringpatternDate="\\[[^[]]+\\]";
【源代码】
importjava.util.regex.*;
publicclassRegexLog{
publicstaticvoidmain(String[]args){
StringpatternIP="\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}";
StringpatternDate="\\[[^\\[]+\\]";
Stringtext="127.0.0.1-frank[10/Oct/2000:
13:
55:
36-0700]"+"\""+"GET/apache_pb.gifHTTP/1.0"+"\""+"2002326";
Patternpattern1=Ppile(patternIP,Pattern.CASE_INSENSITIVE);
Patternpattern2=Ppile(patternDate,Pattern.CASE_INSENSITIVE);
Matchermatcher1=pattern1.matcher(text);
Matchermatcher2=pattern2.matcher(text);
Stringip=null;
Stringdate=null;
while(matcher1.find()){
ip=matcher1.group();
}
System.out.println("IPis"+ip);
while(matcher2.find()){
date=matcher2.group();
}
System.out.println("Dateis"+date);
}
}
程序输出:
IPis127.0.0.1
Dateis[10/Oct/2000:
13:
55:
36-0700]
4.结束语
许多语言,包括Perl、PHP、Python、JavaScript,都支持用正则表达式处理文本,一些文本编辑器用正则表达式实现高级“搜索-替换”功能。
本文只是列出了正则表达式一些常见的应用,要精通正则表达式还需要多多编程实践。