您的位置:首页 > 其它

LintCode Url Parser

2016-06-26 09:25 691 查看
原题网址:http://www.lintcode.com/en/problem/url-parser/

Parse a html page, extract the Urls in it.
Hint: use regex to parse html.

Have you met this question in a real interview?

Yes

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);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  lintcode