Split string with | separator in java

前端 未结 12 723
旧时难觅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条回答
  • The parameter to split method is a regex, as you can read here. Since | has a special meaning in regular expressions, you need to escape it. The code then looks like this (as others have shown already):

    String[] separated = line.split("\\|");
    
    0 讨论(0)
  • 2020-12-06 04:51

    | means OR in regex, you should escape it. What's more, a single '\', you get '\|' means nothing in Java string. So you should also escape the '\' itself, which yields '\|'.

    Good luck!

    0 讨论(0)
  • 2020-12-06 04:52

    you can replace the pipe with another character like '#' before spliting, try this

    String[] seperated = line.replace('|','#').split("#");
    
    0 讨论(0)
  • 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, "|");
    
    0 讨论(0)
  • 2020-12-06 04:55

    Try this: String[] separated = line.split("\\|");

    My answer is better. I corrected the spelling of "separated" :)

    Also, the reason this works? | means "OR" in regex. You need to escape it.

    0 讨论(0)
  • 2020-12-06 04:55

    Escape the pipe. It works.

    String.split("\\|");
    

    The pipe is a special character in regex meaning OR

    0 讨论(0)
提交回复
热议问题