正则表达式删除方括号内的逗号和空格

时间:2017-02-13 02:28:07

标签: java regex

您好我有一个如下所示的文件:

year.", [229, 338], null, [1144, 2371]
year....", null, null, [812]
year:, null, null, [1019, 1028, 2463]
year;, null, [164], [1052]

这就是我希望文件看起来像

year.", 229:338, , 1144:2371
year....", , , 812
year:, , , 1019:1028:2463
year;, , 164, 1052

我试过了.replaceAll(",[?=[^()]*\\]]",":") but this is just replacing all of the commas not the ones inside of the bracket.

1 个答案:

答案 0 :(得分:2)

看起来你想要

  • 删除所有null s
  • number, number, number替换为number:number:number,换句话说,用,
  • 替换前面有数字的每个:
  • 删除[]

演示:

String input = 
        "year.\", [229, 338], null, [1144, 2371]\r\n" + 
        "year....\", null, null, [812]\r\n" + 
        "year:, null, null, [1019, 1028, 2463]\r\n" + 
        "year;, null, [164], [1052]";

String expected = 
        "year.\", 229:338, , 1144:2371\r\n" + 
        "year....\", , , 812\r\n" + 
        "year:, , , 1019:1028:2463\r\n" + 
        "year;, , 164, 1052";

input = input.replace("null", "")
             .replaceAll("(?<=\\d), ", ":")
             .replaceAll("\\[|\\]", "");

System.out.println(input.equals(expected));

输出:true