需要将以下字符串打印为:10-30 03:45:04.312 2760 2760 GrowthKit

字符串为


10-30 03:45:04.312  2760  2760  GrowthKit: job GrowthKit.PeriodicSyncJob   E 

所以输出应该如下所示


10-30

03:45:04.312  

2760  

2760   

GrowthKit: job GrowthKit.PeriodicSyncJob failed  

需要使用正则表达式匹配器和模式来完成。


书面代码:


public static void main(String[] args) {

    String s = "10-30 03:45:04.312  2760  2760  GrowthKit: job GrowthKit.PeriodicSyncJob E ";

    Pattern regex = Pattern.compile("^([a-zA-Z0-9]+).*");

    Matcher matcher = regex.matcher(s);

    while (matcher.find()) {

        for (int i = 0; i < matcher.groupCount(); i++) {

            String[] words = matcher.group(i).split("\\s+");

            for (String line : words) {

                System.out.println("" + line);

            }

        }


    }

}

请为我们提供解决方案:


幕布斯7119047
浏览 208回答 2
2回答

ibeautiful

使用将尝试匹配不同元素的模式\s*([0-9-:.]+|[a-zA-Z:.\s+]+)\s*,它将匹配:组数-:。群信:。空间它适用于所有人,除了最后E一个人,我没有找到分离它的方法Pattern regex = Pattern.compile("\\s*([0-9-:.]+|[a-zA-Z:.\\s+]+)\\s*");Matcher matcher = regex.matcher(s);while (matcher.find()) {&nbsp; &nbsp; String group = matcher.group().trim();&nbsp; &nbsp; System.out.println(group);}10-3003:45:04.31227602760GrowthKit: job GrowthKit.PeriodicSyncJob E如果整个字符串的格式始终相同,则您可以使用一个模式而不是完全匹配它:Pattern regex = Pattern.compile("([0-9-:.]+)\\s+([0-9-:.]+)\\s+([0-9-:.]+)\\s+([0-9-:.]+)\\s+(\\b.*\\b)\\s+(\\w)");Matcher matcher = regex.matcher(s);while (matcher.find()) {&nbsp; &nbsp; for (int i = 1; i <= matcher.groupCount(); i++) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(matcher.group(i));&nbsp; &nbsp; }}10-3003:45:04.31227602760GrowthKit: job GrowthKit.PeriodicSyncJobE

慕沐林林

谢谢cisk,我不想将这些值硬核为“([0-9-:.]+)\s+([0-9-:.]+)\s+([0-9-:.]+ )\s+([0-9-:.]+)\s+(\b.*\b)\s+(\w)");。这样如果字符串最后附加了整数值,它应该正确打印。您能否为此提出另一种解决方案。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java