2013-10-16 111 views
0

我正在使用緩衝讀取器來瀏覽HTML文件&必須用新路徑替換任何img文件的完整URL。與java匹配並替換超鏈接

例如,一個文件,我的工作有3條新的路徑被發現&我已經聲明他們作爲最後的變量:

public static final String x_TAG="https://newsite.com/media/x.jpg"; 
public static final String y_TAG="https://newsite.com/media/y.jpg"; 
public static final String z_TAG="https://newsite.com/media/z.jpg"; 

現在我可以通過文件&模式匹配閱讀這些地方是通過在文件中:

Pattern imgPattern = Pattern.compile("(<\\s*img\\s*alt\\s*=\\s*\").*?(\"\\s*>)"); 
Matcher imgMatcher = imgPattern.matcher(replaceAllTags); 

while(imgMatcher.find()) { 
    System.err.println("match at "+imgMatcher.group()); 
} 

,打印回:

match at <img alt="/oldSite.com/Images?action=AttachFile&amp;do=get&amp;target=Images/x.jpg" src="cc_files/Images_003.jpg" title="/oldSite.com/Images?action=AttachFile&amp;do=get&amp;target=Images/x.jpg" width="600"> 


match at <img alt="/oldSite.com/Images?action=AttachFile&amp;do=get&amp;target=Images/y.jpg" src="cc_files/Images_004.jpg" title="/oldSite.com/Images?action=AttachFile&amp;do=get&amp;target=Images/y.jpg" width="600"> 


match at <img alt="/oldSite.com/Images?action=AttachFile&amp;do=get&amp;target=Images/z.jpg" src="cc_files/Images.jpg" title="/oldSite.com/Images?action=AttachFile&amp;do=get&amp;target=Images/z.jpg" width="600">** 

那麼尋找&的最佳方法是爲每個圖像添加新的URL?

+0

追加後最終結果應該如何? – hwnd

+0
+1

[小馬,他來了..](http://stackoverflow.com/a/1732454/418556) –

回答

0

另一個人試圖與正則表達式匹配屏幕。 :-)我並不是說它不可能,但另一種方法是使用像jsoup https://stackoverflow.com/a/6042593/81520這樣的html解析器或其他類似的庫來解析您讀取的HTML。然後爲每個IMG標記編輯SRC屬性。