有一個用例,我有一個 longString可以包含很多<img>標簽。我需要在串列中收集從 start( <img src=") 到 close( ">) 的整個影像標簽。
我寫了一個 regex( "<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
uj5u.com熱心網友回復:
你可以簡單地這樣做:
final List<String> result = new ArrayList<>();
while (matcher.find()) {
result.add(matcher.group());
}
并擺脫你的final String replace = "";
uj5u.com熱心網友回復:
Java 8 -Pattern.splitAsStream()
我們可以使用所謂的Lookaheads和Lookbehinds拆分給定的字串(有關更多資訊,請查看下面提供的參考資料):
(?<=.)(?=<)- 匹配任何型別的字符和左尖括號之間的位置<(即它捕獲任何字符和標記開頭之間的空子字串)。(?<=>)(?=.)- 匹配右尖括號>和任何型別字符之間的位置。
public static final Pattern ANGLE_BRACKETS =
Pattern.compile("(?<=.)(?=<)|(?<=>)(?=.)");
通過使用此模式,我們生成了一個子字串流,該子字串位于左尖括號和右尖括號邊界上的空字串上。然后過濾代表有效影像標簽的字串。
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";
List<String> imageTags = ANGLE_BRACKETS.splitAsStream(string)
.filter(str -> str.strip().matches("<img[^<] >")) // verifying that a string is a valid image tag
.toList();
imageTags.forEach(System.out::println);
- 有關先行和后行的資訊
在線演示鏈接
Java 9 -Matcher.results()
在正則運算式中,需要注意左尖括號<(不是引號),以確保捕獲的子字串只包含一個標記:
public static final Pattern IMG_TAG = Pattern.compile("img[^<] >");
使用 Java 9 方法Matcher.results(),我們可以創建MatchResult物件流,其中包含有關給定字串中捕獲序列的資訊。而要獲得匹配的子串,我們可以使用MatchResult.group().
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";
List<String> imageTags = IMG_TAG.matcher(string).results() // Stream<MatchResult>
.map(MatchResult::group) // Stream<String>
.toList();
imageTags.forEach(System.out::println);
輸出:
<img src="https://dummyimage.com/300.png/09f/777">
<img src="https://dummyimage.com/300.png/09f/ff2">
<img src="https://dummyimage.com/300.png/09f/888">
<img src="https://dummyimage.com/300.png/09f/2ff">
在線演示鏈接
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/533906.html
標籤:爪哇细绳
