我想替换一个表示Html文件的String,所有相对的链接都是绝对链接。我写了下面的方法,这是行不通的。任何链接后跟一个重复的基础,如http://www.google.dehttp://www.google.de/resource?
public static String replacePattern(URL targetUrl,String urlAsString,String patternString) throws IOException{
System.out.println(targetUrl.toString());
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(urlAsString);
Set<String> replacedStrings = new TreeSet<String>();
//return matcher.replaceAll(targetUrl.toString()+"$0");
while (matcher.find()) {
String relativeLink = matcher.group(1);
//System.out.println("Find Link " + relativeLink);
if(!replacedStrings.contains(relativeLink)){
//System.out.println("Relative Link " + relativeLink);
String newLink = targetUrl.toString() + relativeLink;
//System.out.println("New Link " + newLink);
urlAsString = urlAsString.replace(relativeLink,newLink);
replacedStrings.add(relativeLink);
}
}
return urlAsString;
}
UrlAsString是一个String,其中包含wholecontent作为String.My模式
href=['\"](/[^'\"]+)['\"]
和
src=['\"](/[^'\"]+)['\"]
答案 0 :(得分:0)
使用Class URL:
URL baseUrl = new URL("http://www.domain.com/folder/");
URL url = new URL(baseURL , "url.html");