java Regex - split but ignore text inside quotes?

后端 未结 4 2017
深忆病人
深忆病人 2021-01-15 18:35

using only regular expression methods, the method String.replaceAll and ArrayList how can i split a String into tokens, but ignore delimiters that exist inside quotes? the

4条回答
  •  無奈伤痛
    2021-01-15 19:27

    Use a Matcher to identify the parts you want to keep, rather than the parts you want to split on:

    String s = "hello^world'this*has two tokens'";
    Pattern pattern = Pattern.compile("([a-zA-Z0-9]+|'[^']*')+");
    Matcher matcher = pattern.matcher(s);
    while (matcher.find()) {
        System.out.println(matcher.group(0));
    }
    

    See it working online: ideone

提交回复
热议问题