Split string with | separator in java

前端 未结 12 757
旧时难觅i
旧时难觅i 2020-12-06 04:11

I have a string that\'s like this: 1|\"value\"|;

I want to split that string and have chosen | as the separator.

My code looks like

12条回答
  •  半阙折子戏
    2020-12-06 04:53

    This is a generic method you can use for this purpose. It will handle any delimiter.
    Pattern.quote does the magic.

    import org.apache.commons.lang3.StringUtils;
    
    public static String[] split(String strToSplit, String delimiter) {
        if (StringUtils.isBlank(strToSplit)) {
            return new String[] {};
        } else if (StringUtils.isBlank(delimiter)) {
            return new String[] { strToSplit };
        }
    
        return strToSplit.split(Pattern.quote(delimiter));
    }
    

    In your example:

    String[] separated = split(line, "|");
    

提交回复
热议问题