当前位置: 首页 > 工具软件 > URL Parser > 使用案例 >

LintCode Url Parser

夏学名
2023-12-01

原题网址: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);
        }
    }
}


 类似资料:

相关阅读

相关文章

相关问答