用相对路径替换几个html绝对路径字符串

时间:2014-09-29 15:42:33

标签: java regex replaceall

我有一个html文件和几个从数据库中检索的jpgs。这个html有几个 img scr =“...”标签,每个标签都有一个基于客户网址的绝对路径。 我的任务是在将html和图像文件解压缩到本地驱动器后,用相对路径替换每个绝对路径。

例如,我有:

...
<img src="www.something.com\images\image1.jpg">
...
<img src="www.something.com\images\image2.jpg">
...
<img src="www.something.com\images\image3.jpg">

我想要:

...
<img src="image1.jpg">
...
<img src="image2.jpg">
...
<img src="image3.jpg">

挑战:

1)客户的网址在html文件中都是一样的,但是,另一个html会有不同的客户网址。所以我不能简单地在每个html中查找相同的字符串 2)必须使用java的本机库在java中完成。不能使用Jsoup或任何其他第三方jar。

问题:

我认为replaceAll使用正则表达式是可行的方法,但不确定如何为htmls为不同的客户编写变化的搜索字符串。虽然我已经搜索了堆栈提交的答案,但我还没有找到一个有这种独特场景和挑战的人。

所以我的问题是,完成这项任务的最佳方法是什么?

提前谢谢。

3 个答案:

答案 0 :(得分:0)

正则表达式:

(<img src=\").*?\\\\([^\\\\\"]*\">)

替换字符串:

$1$2

DEMO

答案 1 :(得分:0)

根据文档的大小,我会使用DOM,SAX或STaX。

这是一个使用DOM的快速而肮脏的示例(您需要调整一些更改)。

String minimalHtml = "<html><head></head><body>" +
        "<img src=\"www.something.com/images/image1.jpg\"></img>" + 
        "<img src=\"www.something.com/images/image2.jpg\"></img>" +
        "<img src=\"www.something.com/images/image3.jpg\"></img>" +
        "</body></html>";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(minimalHtml)));
NodeList nl = doc.getElementsByTagName("img");
for (int i = 0; i < nl.getLength(); i++) {
    NamedNodeMap nnm = nl.item(i).getAttributes();
    for (int j = 0; j < nnm.getLength(); j++) {
        String oldValue = nnm.item(j).getNodeValue();
        int index = oldValue.lastIndexOf("/") + 1;
        if (index > -1 && index < oldValue.length()) {
            nnm.item(j).setNodeValue(oldValue.substring(index));
        }
    }
}
// printing out doc
StringWriter sw = new StringWriter();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();

transformer.transform(new DOMSource(doc), new StreamResult(sw));
System.out.println(sw.toString());

<强>输出

<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<img src="image1.jpg"><img src="image2.jpg"><img src="image3.jpg"></body>
</html>

答案 2 :(得分:-1)

(<img\s*src=)".*\\

试试这个。$1"

参见演示。

http://regex101.com/r/nA6hN9/15