【发布时间】:2018-03-21 19:50:35
【问题描述】:
如何限制 Java 中的 Matcher 只匹配所需的 String ?以下是我尝试过的代码,但是预期的匹配应该是“收到发票”,但它在控制台上只打印“发票”。
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class JavaTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
List<String> actionList = new ArrayList<String>();
actionList.add("Invoice");
actionList.add("Invoice Received");
List<String> notes = new ArrayList<String>();
notes.add("Invoice Received123");
for (String note : notes) {
for (String action : actionList) {
Pattern pattern = Pattern.compile(action);
Matcher matcher = pattern.matcher(note);
if(matcher.find()) {
System.out.println("Update History As : "+action);
}
}
}
}
}
【问题讨论】:
-
如果你只是想搜索一个字符串,为什么不直接使用 String.indexOf() 而不是模式匹配
-
您搜索
Invoice,找到并打印出来,然后跳出循环,根本不运行Invoice Received部分。当然,这完全是对正则表达式的滥用。 -
@brso05 它只打印“Invoice”,但我们只需要“Invoice Received”作为输出
标签: java