簡體   English   中英

如何通過匹配正則表達式提取所有子字符串?

[英]How can I extract all substring by matching a regular expression?

我想提取此字符串中所有src屬性的值,我該怎么做:

<p>Test&nbsp;
<img alt="70" width="70" height="50" src="/adminpanel/userfiles/image/1.jpg" />
Test 
<img alt="70" width="70" height="50" src="/adminpanel/userfiles/image/2.jpg" />
</p>

干得好:

String data = "<p>Test&nbsp;\n" +
    "<img alt=\"70\" width=\"70\" height=\"50\" src=\"/adminpanel/userfiles/image/1.jpg\" />\n" +
    "Test \n" +
    "<img alt=\"70\" width=\"70\" height=\"50\" src=\"/adminpanel/userfiles/image/2.jpg\" />\n" +
    "</p>";
Pattern p0 = Pattern.compile("src=\"([^\"]+)\"");
Matcher m = p0.matcher(data);
while (m.find())
{
  System.out.printf("found: %s%n", m.group(1));
}

大多數regex風格都有獲取所有匹配項的捷徑,例如Ruby的scan方法或.NET的Matches() ,但是在Java中,您總是必須將其拼寫清楚。

想法-圍繞'“'字符,看一下每個部分是否包含屬性名稱src ,如果是,則存儲下一個值,即src屬性。

String[] parts = thisString.split("\"");  // splits at " char
List<String> srcAttributes = new ArrayList<String>();
boolean nextIsSrcAttrib = false;
for (String part:parts) {
  if (part.trim().endsWith("src=") {
    nextIsSrcAttrib = true; {
  else if (nextIsSrcAttrib) {
    srcAttributes.add(part);
    nextIsSrcAttrib = false;
  }
}

更好的主意-將其輸入到通常的html解析器中,並從所有img元素中提取所有src屬性的值。 但是以上內容應該是一個簡單的解決方案,尤其是在非生產代碼中。

抱歉,沒有對它進行編碼(時間短),該怎么做:1.(假設文件大小合理)將整個文件讀取為String。 2.拆分字符串arround“ src = \\”“(假定結果數組稱為strArr)3.循環遍歷字符串數組並存儲strArr [i] .substring(0,strArr [i] .indexOf(” \\ “ />”))到一些圖像源集合。

阿維亞德

由於您已請求正則表達式實現...

import java.util.regex.Matcher; 
import java.util.regex.Pattern;

public class Test {
    private static String input = "....your html.....";

    public static void main(String[] args) {
        Pattern pattern = Pattern.compile("src=\".*\"");
        Matcher matcher = pattern.matcher(input);
        while (matcher.find()) {
            System.out.println(matcher.group());
        }

    } 
}

如果您的src屬性未用雙引號引起來,則可能需要調整正則表達式

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM