在 SOF 上,我閱讀了有關 match 與 find 的內容,并在我的正則運算式中附加了一個 。
我不能使用 find 因為我正在嘗試使用流。(我不知道如何將 find 與流一起使用)
這些是我應用正則運算式的行:https ://regex101.com/r/THZpM6/1
下面的作業(沒有流):
String regex_class = "\"class[0-9] \" ";
List<String> matches = new ArrayList<>();
Pattern p = Pattern.compile(regex_class);
for(String line : logEntries) {
Matcher m = p.matcher(line);
if(m.find())
matches.add(m.group());
}
System.out.println(matches); // ["class0", "class1", "class2", "class3"]
我正在嘗試使用流,但它不匹配任何東西。嘗試了2種方法:
String regex_class = "\"class[0-9] \" ";
// 1st try
final Pattern p = Pattern.compile(regex_class);
List<String> result_line1 = logEntries.stream()
.filter(e -> p.matcher(e).matches())
.collect(Collectors.toList());
System.out.println("result_line1 " result_line1.size()); // size is 0
// 2nd try
List<String> result_class = logEntries.stream()
.filter(line -> line.matches(regex_class))
.collect(Collectors.toList());
System.out.println("result_class " result_class.size()); // size is 0
uj5u.com熱心網友回復:
此問題與流無關。您對流和for-loop 使用的方法具有不同的行為。
來自第一個流的方法Matcher.matches()
嘗試將整個區域與模式匹配。
方法String.matches()的行為方式相同。
即有效地,您將流元素與以下正則運算式匹配"^\"class[0-9] \" $"。
for但是在您使用的帶有 -loop 的片段中Matcher.find(),它“嘗試查找與模式匹配的輸入序列的下一個子序列”,即它正在尋找匹配的子序列和(不一定應該是整個字串)。
@shmosel在評論中提供了正確的基于流的解決方案。
或者,我們可以使用 Java 16mapMulty()組合在一個步驟中執行過濾和映射:
List<String> logEntries = // initializing the list
Pattern p = Pattern.compile("\"class[0-9] \" ");
List<String> matches = logEntries.stream()
.map(p::matcher)
.<String>mapMulti((matcher, consumer) -> {
if (matcher.find()) consumer.accept(matcher.group());
})
.toList();
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/527239.html
