【问题标题】:Extract a substring from string message in logback pattern从 logback 模式中的字符串消息中提取子字符串
【发布时间】:2021-08-01 00:36:52
【问题描述】:

我实际上是在尝试使用 with 日志模式提取日志消息的一部分,但不知道如何使用 regexp。

这里是一个消息示例: blablablablablabla #APP_ID : xxxxxx, #CUSTOMER_ID: yyyyyyyy

我看到了 logback 文档,并看到了这个命令 replace(p){r, t},它被放在 appplicatif.yml 的日志模式中。 p 是我上面的消息示例。我只想提取并显示 xxxxxx 或 yyyyyyyy,但我不是正则表达式专家,我不知道如何操作,或者是否可以使用此命令替换。

有人可以帮助我吗?

提前致谢。

【问题讨论】:

    标签: java regex spring-boot logback


    【解决方案1】:

    您可以使用regex((?<=#APP_ID\s?:)\s*[^,\s]*)|((?<=#CUSTOMER_ID\s?:)\s*[^,\s]*)。使用 group(1) 获取 APP_ID 的值,使用 group(2) 获取 CUSTOMER_ID 的值。

    • (: 捕获组开始(1)
      • (?<=: 积极后向断言的开始
        • #APP_ID:字符串文字,#APP_ID
        • \s?:可选空格
        • ::字符文字,:
      • ): 积极的后向断言结束
      • \s*:零个或多个空白字符
      • [^,\s]*:逗号和空格以外的任何字符,任意次数
    • ): 捕获组结束(1)
    • |:或者

    捕获组(2)的描述类似。

    演示:

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class Main {
        public static void main(String[] args) {
            String str = "blablablablablabla #APP_ID : xxxxxx, #CUSTOMER_ID: yyyyyyyy";
            Matcher matcher = Pattern.compile("((?<=#APP_ID\\s?:)\\s*[^,\\s]*)|((?<=#CUSTOMER_ID\\s?:)\\s*[^,\\s]*)")
                    .matcher(str);
    
            while (matcher.find()) {
                String appId = matcher.group(1);
                String customerId = matcher.group(2);
                if (appId != null && !appId.isBlank())
                    System.out.println("APP_ID: " + appId);
                if (customerId != null && !customerId.isBlank())
                    System.out.println("CUSTOMER_ID: " + customerId);
            }
        }
    }
    

    输出:

    APP_ID: xxxxxx
    CUSTOMER_ID: yyyyyyyy
    

    从 Java SE 7 开始,还支持命名捕获组,例如在以下代码中,我将 group(1) 命名为 appId,将 group(2) 命名为 customerId

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class Main {
        public static void main(String[] args) {
            String str = "blablablablablabla #APP_ID : xxxxxx, #CUSTOMER_ID: yyyyyyyy";
            Matcher matcher = Pattern
                    .compile("(?<appId>(?<=#APP_ID\\s?:)\\s*[^,\\s]*)|(?<customerId>(?<=#CUSTOMER_ID\\s?:)\\s*[^,\\s]*)")
                    .matcher(str);
    
            while (matcher.find()) {
                String appId = matcher.group("appId");
                String customerId = matcher.group("customerId");
                if (appId != null && !appId.isBlank())
                    System.out.println("APP_ID: " + appId);
                if (customerId != null && !customerId.isBlank())
                    System.out.println("CUSTOMER_ID: " + customerId);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-12-07
      • 2022-01-23
      • 2011-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-29
      • 2021-12-23
      相关资源
      最近更新 更多