使用 Java 字符串方法replaceAll(regex, replacement)
在哪里
String regex = "(http://server\\.com/)[^<]+(/[^<]+)";
和
String directory = "images";
String replacement = "$1" + directory + "$2";
这将转
http://server.com/stuff1/img1.jpg
进入
http://server.com/images/img1.jpg
例如:
String content = "<img src=\"http://server.com/stuff1/img1.jpg\"><img src=\"http://server.com/stuff1/img2.jpg\"><img src=\"http://server.com/stuff1/img3.jpg\">"
String regex = "(http://server\\.com/).+(/img1\\.jpg)";
String directory = "images";
String replacement = "$1" + directory + "$2";
content = content.replaceAll(regex, replacement);
System.out.println(content);
将输出:
<img src="http://server.com/images/img1.jpg"><img src="http://server.com/images/img2.jpg"><img src="http://server.com/images/img3.jpg">
如果您想跳过完整的主机名并使用相对路径更改replacement
为:
String replacement = directory + "$2";
这将转
http://server.com/stuff1/img1.jpg
进入
images/img1.jpg