LintCode Url Parser

原题网址:http://www.lintcode.com/en/problem/url-parser/

Parse a html page, extract the Urls in it.

Hint: use regex to parse html.

Example

Given the following html page:

<html>
  <body>
    <div>
      <a href="http://www.google.com" class="text-lg">Google</a>
      <a href="http://www.facebook.com" style="display:none">Facebook</a>
    </div>
    <div>
      <a href="https://www.linkedin.com">Linkedin</a>
      <a href = "http://github.io">LintCode</a>
    </div>
  </body>
</html>

You should return the Urls in it:

[
  "http://www.google.com",
  "http://www.facebook.com",
  "https://www.linkedin.com",
  "http://github.io"
]
方法:正则表达式,重点是各种奇葩的情况。

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


public class HtmlParser {
    // Pattern pattern1 = Pattern.compile("(href\\s*=\\s*\")([^\"]*?)(\")", Pattern.CASE_INSENSITIVE);
    // Pattern pattern2 = Pattern.compile("(href\\s*=\\s*')([^']*?)(')", Pattern.CASE_INSENSITIVE);
    Pattern pattern = Pattern.compile("(href\\s*=\\s*[\"']?)([^\"'\\s>]*)([\"'>\\s])", Pattern.CASE_INSENSITIVE);
    /**
     * @param content source code
     * @return a list of links
     */
    public List<String> parseUrls(String content) {
        // Write your code here
        List<String> results = new ArrayList<>();
        Matcher matcher = pattern.matcher(content);
        match(matcher, results);
        return results;
    }
    
    private void match(Matcher matcher, List<String> results) {
        while (matcher.find()) {
            String url = matcher.group(2);
            if (url.length() == 0 || url.startsWith("#")) continue;
            results.add(url);
        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值