Java正则表达式:让分组group()代替replaceAll吧!

来源:互联网 发布:linux 管道符什么作用 编辑:程序博客网 时间:2024/05/16 09:15

今天,在论坛回复贴子时,无意中进一步学到了分组的用法。

在之前几个抓取网页并分析获得标题和超链接的时候,为了去除标题和超链接中多余的字符串,我都是使用

String方法中的replaceAll. 现在掌握了这个分组,完全可以在获取所需内容时就屏蔽了多余的字符串。

下面用例子说话吧!

在前段时间,在论坛回复一个关于正则表达式的贴子http://topic.csdn.net/u/20080401/22/71a948f9-e90c-4bf9-aa01-87eed94126c1.html时,我写了这么个代码:

 

/*
在String s中提取下面的字符串:
http://www.92mp3.com/lrc/lrc.asp?ac=down&id=17656&gq=晴天
*/


import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test 
{
 
 
public static void main(String[] args)
 
{
         String s
="<a href="http://www.92mp3.com/lrc/lrc.asp?ac=down&id=17656&gq=晴天" target=_blank>LRC歌词来自:http://www.92mp3.com/lrc/lrc.asp?ac=down&id=17656&gq=晴天  </a>";  
        String regex
="LRC歌词来自:http://.*?</a>";
        Matcher mt
=Pattern.compile(regex).matcher(s);
        
while(mt.find())
        
{
             String LRCurl
=mt.group().replaceAll("LRC歌词来自:|</a>","");
            
             System.out.println(
"您需要的网址为:"+LRCurl);
             
        }

 }

 
}

这是当时写的代码。现在运用分组写个更简洁的代码:

 

package test1;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test6 
{
 
 
public static void main(String[] args)
 {
         String s
="<a href="http://www.92mp3.com/lrc/lrc.asp?ac=down&id=17656&gq=晴天" target=_blank>LRC歌词来自:http://www.92mp3.com/lrc/lrc.asp?ac=down&id=17656&gq=晴天  </a>";  
        String regex
="LRC歌词来自:(http://.*?)</a>";
        Matcher mt
=Pattern.compile(regex).matcher(s);//此处为改动部分
        while(mt.find())
        {
             String LRCurl
=mt.group(1);//此处为改动部分
            
             System.out.println(
"您需要的网址为:"+LRCurl);
             
        }
 }
 
}

 

 

上面这个程序很小,可能看不出什么优势。

但是,实际上我之前写过的几个程序,比如 http://blog.csdn.net/zhuche110/archive/2008/03/31/2232765.aspx,应用上面的策略,完全可以省略1/3的代码,真有一种如释重负的感觉!

Java学习就是要多看、多思、多练。

一天进步一点,有时灵感一来,收获的可能就是一大片了.

原创粉丝点击