2012-12-13 53 views
0

我有一個字符串,其中包含一些值,如下所示。我想用一些新文本替換包含特定customerId的html img標籤。我想這是不是給我的期望output.here是節目信息小型的Java程序爲什麼這個正則表達式沒有給出預期的輸出?

我輸入的字符串

String inputText = "Starting here.. <img src=\"getCustomers.do?custCode=2&customerId=3334&param1=123/></p>" 
    + "<p>someText</p><img src=\"getCustomers.do?custCode=2&customerId=3340&param2=456/> ..Ending here"; 

正則表達式是

String regex = "(?s)\\<img.*?customerId=3340.*?>"; 

新的文本,我想把裏面輸入串

編輯啓動:

String newText = "<img src=\"getCustomerNew.do\">"; 

編輯完:

我現在做

String outputText = inputText.replaceAll(regex, newText); 

輸出

Starting here.. Replacing Text ..Ending here 

但我預計產量

Starting here.. <img src=\"getCustomers.do?custCode=2&customerId=3334&param1=123/></p><p>someText</p>Replacing Text ..Ending here 

請注意在我的預期輸出中,只有包含customerId = 3340的img標籤被替換文本替換。我沒有得到爲什麼在輸出我得到這兩個img標籤獲得replced?

+1

你解析與正則表達式,只是從未工程完全的HTML(這是一般不是你regexing技能正則表達式的限制) –

+0

你使用的是錯誤的tool..use HTML解析器 – Anirudha

+0

@ Some1.Kill.The.DJ你能幫我一下,我怎樣才能得到像jsoup這樣的html解析器的預期結果? –

回答

1

正如其他人在評論中告訴你的,HTML不是一種常規語言,所以使用正則表達式來操縱它通常是痛苦的。您最好的選擇是使用HTML解析器。我以前沒有使用過Jsoup,但谷歌搜索一點點,似乎你需要的東西,如:

import org.jsoup.*; 
import org.jsoup.nodes.*; 
import org.jsoup.select.*; 

public class MyJsoupExample { 
    public static void main(String args[]) { 
     String inputText = "<html><head></head><body><p><img src=\"getCustomers.do?custCode=2&customerId=3334&param1=123\"/></p>" 
      + "<p>someText <img src=\"getCustomers.do?custCode=2&customerId=3340&param2=456\"/></p></body></html>"; 
     Document doc = Jsoup.parse(inputText); 
     Elements myImgs = doc.select("img[src*=customerId=3340"); 
     for (Element element : myImgs) { 
      element.replaceWith(new TextNode("my replaced text", "")); 
     } 
     System.out.println(doc.toString()); 
    } 
} 

基本上代碼獲取img節點列表與src屬性包含給定的字符串

Elements myImgs = doc.select("img[src*=customerId=3340"); 

然後遍歷列表並用一些文本替換這些節點。

UPDATE

如果您不想替換文本整個img節點,而是你需要給一個新的價值,它的src屬性,那麼可以更換for循環與塊:

element.attr("src", "my new value")); 

,或者如果你想改變只是一個src值的部分,那麼你可以這樣做:

String srcValue = element.attr("src"); 
element.attr("src", srcValue.replace("getCustomers.do", "getCustonerNew.do")); 

這與我發佈的in this thread非常相似。

+0

Vicent. It works good. But i am getting one issue.Instead of "my replaced text", Use "「jsoup作出這樣< IMG SRC = " getCustomerNew.do "/>代替的元件; –

+0

看起來是這樣做的編碼字符,如<,」我怎樣才能停止? –

+0

所以你不想把整個img節點替換爲src屬性的值? – Vicent

4

你有「通配符」 /「任何」模式(.*)在那裏,這將延長比賽時間最長的可能匹配的字符串,並且在模式的最後一個固定的文本是>字符,因此這匹配輸入文本中的最後一個>字符,即最後一個!

您應該可以通過將.*零件更改爲類似[^>]+的東西來解決此問題,以便匹配不會跨越第一個>字符。

用正則表達式解析HTML肯定會引起痛苦。

+0

你是對的,但他使用'。*?'而不是'。*' – Anirudha

+0

@Greg我可以通過jsoup庫獲得預期的輸出嗎? –

+0

'。*?'實際上與'。*'沒有任何區別。零個或多個字符的零個或多個匹配是零個或多個字符,包括任意數目的'>'字符。 –

0

會發生什麼事是你的正則表達式開始第一IMG標籤相匹配,然後消耗的一切(無論是貪婪與否),直到它找到客戶ID = 3340,然後繼續消費的一切,直到它找到>

如果你希望它僅消耗了IMG客戶ID = 3340想起了什麼,使得從它可以匹配其他標籤不同,這標籤。

在這種特殊情況下,一種可能的解決方案是使用後視運算符(不會消耗匹配項)來查看標記後面的內容。此正則表達式將工作:

String regex = "(?<=</p>)<img src=\".*?customerId=3340.*?>"; 
相關問題