Escape comma when using String.split

前端 未结 4 1124
野趣味
野趣味 2020-12-08 20:58

I\'m trying to perform some super simple parsing o log files, so I\'m using String.split method like this:

String [] parts = input.split(\",\");         


        
4条回答
  •  -上瘾入骨i
    2020-12-08 21:50

    I'm afraid, there's no perfect solution for String.split. Using a matcher for the three parts would work. In case the number of parts is not constant, I'd recommend a loop with matcher.find. Something like this maybe

    final String s = "type=simple, output=Hello, world, repeat=true";
    final Pattern p = Pattern.compile("((?:[^\\\\,]|\\\\.)*)(?:,|$)");
    final Matcher m = p.matcher(s);
    while (m.find()) System.out.println(m.group(1));
    

    You'll probably want to skip the spaces after the comma as well:

    final Pattern p = Pattern.compile("((?:[^\\\\,]|\\\\.)*)(?:,\\s*|$)");
    

    It's not really complicated, just note that you need four backslashes in order to match one.

提交回复
热议问题