我想用一个字符串替换一个字符串,它代表一个 Html 文件,所有相对链接都用绝对链接。我写了以下方法,它不起作用。任何链接后跟一个重复的 baseurl,如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 是一个字符串,其中包含作为字符串的全部内容。我的模式是
href=['\"](/[^'\"]+)['\"]
和
src=['\"](/[^'\"]+)['\"]