簡體   English   中英

正則表達式模式使用逗號分隔值,但保留括號內使用的逗號

[英]Regex pattern to separate values using comma but retain commas used within parenthesis

我正在嘗試修改正則表達式,使其保留括號內使用的逗號並分隔所有其他值。

現有模式: ([^\\s,]+)\\s*=>([^,]+)更新模式: ([^\\s,]+)\\s*=>([^(,)]+)

Java代碼:


    public static void main(String[] args) {

        String softParms = "batch_code => 'batchCd',user_id => 'SYSUSER',thread_pool => 'tpName',business_date => FN_DATE_ARG(null,0),rerun_number => 0,max_timeout_mins => 0,raise_error => false,thread_notifications => false";

         //Pattern paramPattern = Pattern.compile("([^\\s,]+)\\s*=>([^,]+)");
        Pattern paramPattern = Pattern.compile("([^\\s,]+)\\s*=>([^(,)]+)");
        Matcher matcher = paramPattern.matcher(softParms);
        while (matcher.find()) {
            String param = matcher.group(1);
            String value = matcher.group(2);
            System.out.println("Param: " + param + ", Value: " + value);
        }
    }

business_date的參數值應為FN_DATE_ARG(null,0)但 function 要么返回FN_DATE_ARG(null要么FN_RMB_DATE_ARG

將不勝感激任何幫助!

您可以使用

([^\s,]+)\s*=>\s*(.*?)(?=\s*,\s*\w+\s*=>|$)

請參閱正則表達式演示 細節:

  • ([^\s,]+) - 第 1 組:除空格和逗號之外的一個或多個字符
  • \s*=>\s* - =>用零個或多個空格括起來
  • (.*?) - 第 2 組:除換行符之外的任何零個或多個字符盡可能少
  • (?=\s*,\s*\w+\s*=>|$) - 直到最左邊的 0+ 個空格、逗號、0+ 個空格、1+ 個單詞字符、0+ 個空格、 =>或字符串的結尾。

在您的代碼中,使用

Pattern paramPattern = Pattern.compile("([^\\s,]+)\\s*=>\\s*(.*?)(?=\\s*,\\s*\\w+\\s*=>|$)");

在線查看 Java 演示

當只需要對String#replaceAll進行單行調用時,為什么要使用過於復雜的正則表達式:

String softParms = "batch_code => 'batchCd',user_id => 'SYSUSER',thread_pool => 'tpName',business_date => FN_DATE_ARG(null,0),rerun_number => 0,max_timeout_mins => 0,raise_error => false,thread_notifications => false";
String businessDate = softParms.replaceAll(".*\\bbusiness_date => (.*?)\\s*(?:,[^,\\s]+ =>.*|$)", "$1");
System.out.println(businessDate);

這打印:

FN_DATE_ARG(null,0)

正則表達式模式將匹配鍵business_date后跟\\s*,[^,\\s]+ => ,在這種情況下將匹配文本FN_DATE_ARG(null,0) (.*?)匹配組將在下一個鍵之前的逗號處停止匹配。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM