在一个用例中,我有一个很长的 String
其中可以包含许多<img>
标签。
我需要在列表中收集从开始( <img src="
)到关闭( ">
)的整个图像标签。
我编写了一个正则表达式( "<img.*?\">"gm
)来选择这些,但不知道如何将它们全部收集到列表中。
例如:
final String regex = "<img.*?\\\">";
final String string = "Hello World <img src=\"https://dummyimage.com/300.png/09f/777\"> \nMy Name <img src=\"https://dummyimage.com/300.png/09f/ff2\"> Random Text\nHello\nHello Random <img src=\"https://dummyimage.com/300.png/09f/888\"> \nMy Name <img src=\"https://dummyimage.com/300.png/09f/2ff\">adaad\n";
final String replace = "";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
final String result = matcher.replaceAll(replace); // Here, how can I collect all the image tags in a list
最佳答案
您可以简单地执行以下操作:
final List<String> result = new ArrayList<>();
while (matcher.find()) {
result.add(matcher.group());
}
并删除你的final String Replace = "";
关于java - 将表示 <img> 标签的字符串部分收集到 Java 8 中的列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74448333/