简体   繁体   English

无法解析JAVA中的正则表达式

[英]Unable to Parse reqular expression in JAVA

This is my code, 这是我的代码

String xyz = "{\"status\":\"ok\",\"data\":[{\"RatingCount\":4}],         [{\"RatingCount\":1}], [{\"RatingCount\":1}]\"code\":1}";
    String pattern = ".*],\\s*\\[.*";//"(.*)(],\\s.*\\[)(.*)";
    Pattern p1 = Pattern.compile(pattern);
    Matcher m1 = p1.matcher(xyz);
    boolean b = m1.matches();
    System.out.println(b);

I would like to replace pattern '], [' with "" . 我想将模式'], ['替换为""

I used replaceAll but no luck 我用replaceAll但没有运气

Check it in working Fiddle 在工作的小提琴中检查

Use the regex as below 使用正则表达式如下

String pattern = "\],[ ]*\[";

xyz =xyz.replaceAll("]\\s*,\\s*\\[", "],["); xyz = xyz.replaceAll(“] \\ s *,\\ s * \\ [”,“],[”);;

This worked like charm and also this link helped me alot http://regexr.com/ 这就像魅力一样起作用,并且此链接也帮助我很多http://regexr.com/

Thank you for all your inputs! 感谢您的所有投入!

The output of this block is: {"status":"ok","data":[{"RatingCount":4}{"RatingCount":1}{"RatingCount":1}]"code":1} 该块的输出是: {"status":"ok","data":[{"RatingCount":4}{"RatingCount":1}{"RatingCount":1}]"code":1}

public static void main(String[] args) {
    String str = "{\"status\":\"ok\",\"data\":[{\"RatingCount\":4}],         [{\"RatingCount\":1}], [{\"RatingCount\":1}]\"code\":1}";
    System.out.println(replace(str, "\\],\\s+\\["));
  }

  public static String replace(String str, String regex) {
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(str);
    return matcher.replaceAll("");
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM