这篇文章给大家介绍如何在Java项目中的链接地址怎么利用正则表达式获取,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
1、正则表达式中Matcher中find()
方法的应用。
2、String对象中的 replaceAll(String regex,String replacement)
方法的使用。通过这个方法去除了不必要的字符串,从而得到了需要的网址和链接文字
例1.超简单的
String content = "<a href="URL" rel="external nofollow" >";
String pattern= "href="([^" rel="external nofollow" ]*)"";
Pattern p = Pattern.compile(pattern, 2 | Pattern.DOTALL);
Matcher m = p.matcher(content);
if(m.find()) {
System.out.println("url="+m.group(1));
}
例2.上面只能获取带有双“号的a标题中的url,下面我们加以改进可以获取任何状态下的a标题url
package com.gong.example;
import Java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Simple {
public static void main(String[] args){
String input="<a href = "https://www.jb51.net" target="_blank" >www.jb51.net</a>" +
"<a href = 'http://www.163.com' target='_blank' >www.163.com</a> " +
"<a href=http://www.yahoo.com target=_blank >www.yahoo.com</a>";
String patternString = "\s*(?i)href\s*=\s*("([^"]*")|'[^']*'|([^'">\s]+))"; //href
Pattern pattern = Pattern.compile(patternString,
Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
String link=matcher.group();
System.out.println(link);
link=link.replaceAll("href\s*=\s*(['|"]*)", "");
System.out.println("--"+link);
link=link.replaceAll("['|"]", "");
System.out.println("---"+link);
}
}
}
例3.我们还可以利用它进行升级获取 获取网址和链接文字哦。
/*
功能说明:分析字符串s,提取s里面的超链接和链接文字
*/
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegTest
{
public static void main(String[] args)
{
//String s="<p id=km> <a href=http://down.yourweb.com>空间</a> | <a ";
String s="</p><p style=height:14px><a href=http://mb.yourweb.com>企业推广</a> | <a href=http://code.yourweb.com>搜索风云榜</a> | <a href=/home.html>关于百度</a> | <a href=http://www.yourweb.com>About Baidu</a></p><p id=b>©2008 Baidu <a href=http://www.yourweb.com>使用百度前必读</a> <a href=http://www.miibeian.gov.cn target=_blank>京ICP证03xxxx号</a> <a href=https://www.jb51.net><img src=/get_pic/2013/11/22/20131122031447947.gif></a></p></center></body></html><!--543ff95f18f36b11-->";
String regex="<a.*?/a>";
//String regex = "<a.*>(.*)</a>";
Pattern pt=Pattern.compile(regex);
Matcher mt=pt.matcher(s);
while(mt.find())
{
System.out.println(mt.group());
System.out.println();
String s2=">.*?</a>";//标题部分
String s3="href=.*?>";
Pattern pt2=Pattern.compile(s2);
Matcher mt2=pt2.matcher(mt.group());
while(mt2.find())
{
System.out.println("标题:"+mt2.group().replaceAll(">|</a>",""));
}
Pattern pt3=Pattern.compile(s3);
Matcher mt3=pt3.matcher(mt.group());
while(mt3.find())
{
System.out.println("网址:"+mt3.group().replaceAll("href=|>",""));
}
}
}
}
关于如何在Java项目中的链接地址怎么利用正则表达式获取就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。