【问题标题】:Java regular expression to get submetric from logfilesJava正则表达式从日志文件中获取子指标
【发布时间】:2021-10-26 07:20:02
【问题描述】:

我正在尝试从包含数千行的日志中获取子指标。 这些线不相似,所以我需要在获取子度量之前匹配一些值。

一些简化的示例行

1, 2, acceptline,x,111, 100, , , 20, 20, end
1, 2, declineline,x,x, 100, 20, , end
1, 2, 3, acceptline,x,x, 1000, , 40, end

我尝试获取值匹配后第三个逗号分隔列中的数值(接受行)。

在我的示例中,这些值是 100 和 1000,但它们基本上可以是任何数值

我已经通过下面的 java 正则表达式成功地得到了正确的子度量值

^.*acceptline.+?((?<submetric>,.+?){3}),.*

但是在那个正则表达式中,我得到了子度量 &lt;, 100&gt; 或者那个数值是什么。 现在我需要改进该正则表达式,以便在接受为子度量之前删除那些领先的 ​​。

【问题讨论】:

    标签: java regex


    【解决方案1】:

    你可以使用

    \bacceptline(?:,[^,]*){2},\s*(\d+)
    

    如果数字可以是浮点数,请使用\d*\.?\d+ 而不是\d+

    请参阅regex demo详情

    • \b - 单词边界
    • acceptline - 一句话
    • (?:,[^,]*){2} - 出现两次逗号,然后出现零个或多个非逗号
    • , - 逗号
    • \s* - 零个或多个空格
    • (\d+) - 第 1 组:一位或多位数字。

    Java demo

    String string = "1, 2, acceptline,x,111, 100, , , 20, 20, end\n1, 2, declineline,x,x, 100, 20, , end\n1, 2, 3, acceptline,x,x, 1000, , 40, end";
            
    String regex = "\\bacceptline(?:,[^,]*){2},\\s*(\\d+)";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(string);
            
    while (matcher.find()) {
        System.out.println(matcher.group(1));
    }
    // => 100 and 1000
    

    【讨论】:

    • 我使用 regex101.com 来尝试检查我的正则表达式。至少该工具与 \\bacceptline(?:,[^,]*){2},\\s*(\\d+) 正则表达式不匹配。
    • @Rahmaputra 那个工具完美finds two matches。如果代码有问题,该工具也可以generates the code for you
    • 我得到了它的工作,但它不适合我的目的。
    • @Rahmaputra 不知道你的目的是什么,它超出了范围。
    • 我实际上并没有编写任何代码,而是配置使用 java regex 的度量解析器工具。该工具使用子度量值作为标签。所以我需要将 100|1000 解析为子度量值。
    【解决方案2】:

    关于 regex101.com,我终于明白了。

    ^.*acceptline.+?((,[^\,]*){1}),\s*(?<submetric>\d+).*
    

    感谢 Wiktor 用这些 \s 和 \d 开关推动我的正确方式。

    【讨论】:

    • 如果它解决了您的问题,您可能会接受自己的答案。请注意,您可以从 15 个声望点中upvote 选择您认为有用的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多