日期:2014-05-20  浏览次数:20691 次

正则表达式替换url
请教各位网友,下面这个正则表达式改怎样写?
原始代码是这样:

<div style="background-color: #cccccc; margin: 5px auto; width: 215px; height: 215px">
<a href="http://XXX/t?id=XXX" target="_blank" title="XXX"><img src="http://XXX/aaa.jpg" style="width: 213px; height: 213px" /> </a></div>
<div style="line-height: 14px; background-color: #fff; margin: 5px auto; width: 215px; height: 14px">

现在我只想替换掉<a href>标签中的url,在"<"可能有多个空格或者其他字符,在“a”与“href”之间可能存在其他的元素(例如可能是<a title="XXX" href="XXX">),请问这个url该怎么写呢?
正则表达式

------解决方案--------------------
String html = ...;
Document doc = Jsoup.parseBodyFragment(html);
Element a = doc.select("a").first();
a.attr("href", "http://www.baidu.com");
String result = doc.outerHtml();

结果:
<html>
 <head></head>
 <body>
  <div style="background-color: #cccccc; margin: 5px auto; width: 215px; height: 215px">
   <a href="http://www.baidu.com" target="_blank" title="XXX"> <img src="http://XXX/aaa.jpg" style="width: 213px; height: 213px" /> </a>
  </div>
  <div style="line-height: 14px; background-color: #fff; margin: 5px auto; width: 215px; height: 14px"></div>
 </body>
</html>

------解决方案--------------------
String source = "<div style=\"background-color: #cccccc; margin: 5px auto; width: 215px; height: 215px\"><a href=\"http://XXX/t?id=XXX\" target=\"_blank\" title=\"XXX\"><img src=\"http://XXX/aaa.jpg\" style=\"width: 213px; height: 213px\" /> </a></div><div style=\"line-height: 14px; background-color: #fff; margin: 5px auto; width: 215px; height: 14px\">";