gpt4 book ai didi

Java 帮助使用模式操作 anchor

转载 作者:行者123 更新时间:2023-12-02 07:33:40 25 4
gpt4 key购买 nike

我在使用我的程序完成一些事情时遇到了困难,我希望有人能够提供帮助。

我有一个包含 HTML 页面源代码的字符串。

我想要做的是提取以下 HTML 的所有实例并将其放入数组中:

<img src="http://*" alt="*" style="max-width:460px;">

因此,我将拥有一个 X 大小的数组,其中包含与上面类似的值,显然更新了 src 和 alt 属性。

这可能吗?我知道有 XML 解析器,但格式始终相同。

任何帮助将不胜感激。

最佳答案

我建议使用 ArrayList 而不是静态数组,因为看起来您不知道将有多少个匹配项。

对 HTML 使用 REGEX 也不是个好主意,但如果您确定标签始终使用相同的格式,那么我建议:

Pattern pattern = Pattern.compile(".*<img src=\"http://(.*)\" alt=\"(.*)\"\\s+sty.*>", Pattern.MULTILINE);

这是一个例子:

public static void main(String[] args) throws Exception {
String web;
String result = "";
for (int i = 0; i < 10; i++) {
web = "<img src=\"http://image" + i +".jpg\" alt=\"Title of Image " + i + "\" style=\"max-width:460px;\">";
result += web + "\n";
}
System.out.println(result);
Pattern pattern = Pattern.compile(".*<img src=\"http://(.*)\" alt=\"(.*)\"\\s+sty.*>", Pattern.MULTILINE);

List<String> imageSources = new ArrayList<String>();
List<String> imageTitles = new ArrayList<String>();

Matcher matcher = pattern.matcher(result);
while (matcher.find()) {
String imageSource = matcher.group(1);
String imageTitle = matcher.group(2);
imageSources.add(imageSource);
imageTitles.add(imageTitle);

}

for(int i = 0; i < imageSources.size(); i++) {
System.out.println("url: " + imageSources.get(i));
System.out.println("title: " + imageTitles.get(i));

}
}
}

关于Java 帮助使用模式操作 anchor ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12572563/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com