有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

regex java模式从mapper生成的字符串中清除其他字符周围的引号

我需要将json映射器生成的字符串序列替换为fallow:

:"{ -> :{   
}"} -> }} 

你会怎么看呢

更新:完整字符串示例

{"method":"createInvoice","params":"{"btcDue":null,"btcPaid":null,
                        "btcPrice":null,"currency":"PLN","currentTime":null,
                        "exceptionStatus":null,"expirationTime":null,
                        "guid":"99250130","id":null,"invoiceTime":null,
                        "paymentUrls":null,"price":1.23,"rate":null,
                        "status":null,"transactions":null,"url":null
}"} 

但假设我们将有更多实例需要替换,比如2:)

澄清:安卓字符串方法

 public String replace(CharSequence target, CharSequence replacement) {
    String replacementStr = replacement.toString();
    String targetStr = target.toString();
    // Special case when target == "". 
    // .. cut 
    // This is the "regular" case.
    int lastMatch = 0;
    StringBuilder sb = null;
    for (;;) {
        int currentMatch = indexOf(this, targetStr, lastMatch);
        if (currentMatch == -1) {
            break;
        }
        if (sb == null) {
            sb = new StringBuilder(count);
        }
        sb.append(this, lastMatch, currentMatch);
        sb.append(replacementStr);
        lastMatch = currentMatch + targetStr.count;
    }

    if (sb != null) {
        sb.append(this, lastMatch, count);
        return sb.toString();
    } else {
        return this;
    }
 }

 public String replaceAll(String regex, String replacement) {
    return Pattern.compile(regex).matcher(this).replaceAll(replacement);
}

共 (3) 个答案

  1. # 1 楼答案

    您可以使用lookahead/lookbehind结构匹配:+{}+}包围的所有引号:

    (?<=})"(?=})|(?<=:)"(?={)
    

    将此消息传递给replaceAll以删除引号(demo

  2. # 2 楼答案

    没什么难事:

    String result = "{\"method\":\"createInvoice\",\"params\":\"{\"btcDue\":null,\"btcPaid\":null,\"btcPrice\":null,\"currency\":\"PLN\",\"currentTime\":null,\"exceptionStatus\":null,\"expirationTime\":null,\"guid\":\"99250130\",\"id\":null,\"invoiceTime\":null,\"paymentUrls\":null,\"price\":1.23,\"rate\":null,\"status\":null,\"transactions\":null,\"url\":null}\"}"
        .replace(":\"{", ":{")
        .replace("}\"}", "}}");
    System.out.println(result);
    
  3. # 3 楼答案

    按搜索

    \"
    

    然后将其替换为“

    原文

    :"{   
    }"}
    

    结果

    :{
    }}
    

    JAVA代码

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    final String regex = "\\\"";
    final String string = ":\"{ -> :{   \n"
         + "}\"} -> }} ";
    final String subst = "";
    
    final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
    final Matcher matcher = pattern.matcher(string);
    
    // The substituted value will be contained in the result variable
    final String result = matcher.replaceAll(subst);
    
    System.out.println("Substitution result: " + result);