我在 StackOverfow 上閱讀了有關matchvsfind的內容,并在我的正則運算式中附加了一個 。
似乎無法使用find(),因為當我嘗試使用 Stream API 時。我不知道如何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"]
我正在嘗試使用流,但結果不匹配任何東西。
我的嘗試:
String regex_class = "\"class[0-9] \" ";
// 1st attempt
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 attempt
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熱心網友回復:
您可以Matcher.find()成功地與流一起使用。
@shmosel在此評論中提供了一種方法來做到這一點。這是他提出的解決方案(格式化并添加了評論):
List<String> logEntries = // initializing the list
Pattern p = Pattern.compile("\"class[0-9] \" ");
List<String> result_class = logEntries.stream() // Stream<String>
.map(p::matcher) // Stream<Matcher>
.filter(Matcher::find) // Stream<Matcher>
.map(Matcher::group) // Stream<String>
.collect(CollectrotoList());
或者,我們可以使用 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();
您的嘗試沒有成功,因為您對流和for-loop 使用的方法具有不同的行為。
來自第一個流的方法Matcher.matches()
嘗試將整個區域與模式匹配。
方法String.matches()的行為方式相同。
即有效地,您將流元素與以下正則運算式匹配"^\"class[0-9] \" $"。
for但是在您使用的帶有 -loop 的片段中Matcher.find(),它“嘗試查找與模式匹配的輸入序列的下一個子序列”,即它正在尋找匹配的子序列和(不一定應該是整個字串)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/527832.html
