在java中,如何将日志消息与多个字符串模式相匹配
我有几个字符串模式:
ArrayList<String> tmp = new ArrayList<String>();
tmp.add("INFO");
tmp.add("Error");
tmp.add("Debug");
tmp.add("Failed");
tmp.add("Unable");
我还在检查文件中的每一行是否与任何一个字符串模式匹配。如果匹配,我将显示该行。我的代码是,
for (String pattern : tmp) {
if (line.contains(pattern)) {
System.out.println(line);
}
}
现在的问题是,如果行与多个字符串模式,每次匹配时都会显示行。
我只想显示该行一次(需要检查任何字符串模式是否与行匹配)。如何做到这一点。
i have several String patterns:
ArrayList<String> tmp = new ArrayList<String>();
tmp.add("INFO");
tmp.add("Error");
tmp.add("Debug");
tmp.add("Failed");
tmp.add("Unable");
also i am checking the every lines in the file whether lines are matched with any one of the string pattern.if matched,i will display the line.my code is,
for (String pattern : tmp) {
if (line.contains(pattern)) {
System.out.println(line);
}
}
Now the problem is,if line match with more than one string pattern,line gets displayed by every time whenever gets matched.
i want to display the line by only one time(need to check any of the string patterns are matched with line).How to do this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用正则表达式:
这将打印包含一个或多个提供的关键字的每一行。
有关详细信息,请参阅正则表达式教程。
另外,如果您让正则表达式引擎进行行分割而不是传递单独的行,您可以进一步改进这一点:
更新: 好的,如果模式是动态的,您可以从列表中动态构建它:
Use a regular expression:
This will print every line that contains one or more of the supplied keywords.
See the Regular Expression Tutorial for more info.
Also, you could further improve this if you let the regex engine do the line splitting instead of passing individual lines:
Update: Ok, if the pattern is dynamic you can just build it dynamically from your list:
只需在其中添加一个
break
:另外,请正确格式化您的代码(缩进 4 个空格),因为这样更容易阅读。
just put a
break
in there:Also, please properly format your code (indent it with 4 spaces), as it makes it easier to read.