2016-08-02 90 views
2

在我的字符串時,它可能包含單/多「SRC」 ..我想獲取該SRC值鏈接..正則表達式來獲得從HTML字符串的srcattribute

字符串是這樣的:

"<p>Lets take an example</p> 
<p> 
<img alt="\therefore its your address\\" 
src="http://localhost:8080/image?%5Ctherefore%20P%5B1&amp;plus;%5Cfrac% 
%28n-2%29%7D%7B100%7D%5D%3DP%5B1&amp;plus;%5Cfrac%7B4n%7D%7B100%7D%5D%3D930%5C%5C% 
%5C%5C%206n-12%3D4n%5C%5C%202n%3D12%5C%5C%20n%3D6%5C%5C%20%5Ctherefore%20P%5B1&amp;plus 
5Cfrac%7B4%5Ctimes6%7D%7B100%7D%5D%3D930%5C%5C%20P%3D%5Cfrac%7B930%5Ctimes100%7D%7B124%7D%5C%5C%20P%3DRs.%5C%20750" /></p> " 

或可能喜歡:

"<p>Lets take an example</p> <p><img alt="\therefore its your \\" src="http://http://localhost:8080/image?%5Cthe 
refore%20P%281&amp;plus;%5Cfrac%7B20%7D%7B100%7D%29%5En% 
C%20P%281.2%29%5En%3E2P%5C%5C" /></p> <p>its your another address</p> <p>may be your address is<img alt="aoouern " 
src="http://http://localhost:8080/image?281.2%29%5E2P%3D1.44P" /> 
</p> <p>or its 
<img alt="(1.2)^3P=1.728P" src="http://localhost:8080/image?%281.2%29%5E3P%3D1.728P" /> 
</p> <p>or you can do <img alt="lets thake this" 
    src="http://localhost:8080/image?%281.2%29%5E4P%3D2.0736P" /></p> <p>so, your are clear?;</p> " 

我所做的是:

String s = "src="; 
int ix = solution_box.indexOf(s)+s.length(); 
String value = solution_box.substring(ix, solution_box.indexOf("\"", ix+1)); 
value = value.substring(1); 
System.out.println(value); 

當我的字符串中只有一個「src」時,我可以獲取該src值..但是當字符串contactins中有多個src值時,它只會回到一個src值..

我怎樣才能得到多個呢? ?我究竟做錯了什麼??

+0

不要使用正則表達式。使用HTML解析器 – Jens

回答

0

只需使用此代碼:

   Pattern p=null; 
      Matcher m= null; 
      String word0= null; 
      String word1= null; 

      p= Pattern.compile(".*<img[^>]*src=\"([^\"]*)",Pattern.CASE_INSENSITIVE); 
      m= p.matcher(solution_box); 
      while (m.find()) 
        { 
       word0=m.group(1); 
       System.out.println(word0.toString()); 
        } 

正則表達式是不是一個好的做法..