2012-07-10 75 views
1

我有一個包含大量圖像標記的Html字符串,我需要獲取標記並對其進行更改。例如:java:正則表達式

String imageRegex = "(<img.+(src=\".+\").+/>){1}"; 
String str = "<img src=\"static/image/smiley/comcom/9.gif\" smilieid=\"296\" border=\"0\" alt=\"\" />hello world<img src=\"static/image/smiley/comcom/7.gif\" smilieid=\"294\" border=\"0\" alt=\"\" />"; 
Matcher matcher = Pattern.compile(imageRegex, Pattern.CASE_INSENSITIVE).matcher(msg); 
int i = 0; 
while (matcher.find()) { 
    i++; 
    Log.i("TAG", matcher.group()); 
} 

結果是:

<img src="static/image/smiley/comcom/9.gif" smilieid="296" border="0" alt="" />hello world<img src="static/image/smiley/comcom/7.gif" smilieid="294" border="0" alt="" /> 

,但它不是我想要的,我想要的結果是

<img src="static/image/smiley/comcom/9.gif" smilieid="296" border="0" alt="" /> 
<img src="static/image/smiley/comcom/7.gif" smilieid="294" border="0" alt="" /> 

有什麼錯我的正則表達式?

+2

我能請您看看這個答案:http://stackoverflow.com/a/1732454/83109 – 2012-07-10 13:14:25

+0

有什麼不妥,雖然regexing出僅標籤? – 2012-07-10 13:20:32

+0

是的,有。問題在於HTML不是常規語言,所以它不適合用正則表達式進行分析。有時候你可以讓它工作在一個緊急狀態(這可能是其中一種情況),但有點像用舊鞋釘釘子。它可能會完成工作,但它並不是真正的工具。 – 2012-07-10 13:23:50

回答

1

嘗試(<img)(.*?)(/>),這應該做的伎倆,雖然是的,你不應該使用正則表達式來解析HTML,因爲人們會反覆告訴你。

我沒有安裝eclipse,但我有VS2010,這對我很有用。

 String imageRegex = "(<img)(.*?)(/>)"; 
     String str = "<img src=\"static/image/smiley/comcom/9.gif\" smilieid=\"296\" border=\"0\" alt=\"\" />hello world<img src=\"static/image/smiley/comcom/7.gif\" smilieid=\"294\" border=\"0\" alt=\"\" />"; 
     System.Text.RegularExpressions.MatchCollection match = System.Text.RegularExpressions.Regex.Matches(str, imageRegex, System.Text.RegularExpressions.RegexOptions.IgnoreCase); 
     StringBuilder sb = new StringBuilder(); 
     foreach (System.Text.RegularExpressions.Match m in match) 
     { 
      sb.AppendLine(m.Value); 
     } 
     System.Windows.MessageBox.Show(sb.ToString()); 

結果:

<img src="static/image/smiley/comcom/9.gif" smilieid="296" border="0" alt="" /> 
<img src="static/image/smiley/comcom/7.gif" smilieid="294" border="0" alt="" /> 
+0

是的,它的工作原理;我更新的正則表達式 – Mejonzhan 2012-07-10 13:33:04

0

大衛·M是正確的,你真的不應該嘗試這樣做,但你的具體問題是,+量詞在你的正則表達式是貪婪的,所以它會匹配可能匹配的最長的子字符串。

有關量詞的更多詳細信息,請參閱The regex tutorial

+0

非常感謝你,我的答案是你的答案。 – Mejonzhan 2012-07-10 13:37:14