3

I want to split a string each time there's a | in it, but the split method only accepts a regex. The regex | splits the string after each letter, which is not what I want. Using \u007C does the same thing too.

I tried using \|, but that just gives me: Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \\ ).

4 Answers 4

6

You need to do something like this:

\\|

The reason is that in regular expression in order for "|" to be considered as "|" and not as a regex operator you need the "\". But in java you can't just write "\" in a string because that's a save operator in a string. So you have to do \\. Hope that explains it.

Sign up to request clarification or add additional context in comments.

Comments

2

Escape the backslash. You are in a Java string, and it should contain a literal backslash.

"\\|"

Comments

2

Works for me:

import java.util.Arrays;

public class Testing {
    public static void main(String[] args){
        String word= "abc|def";
        String[] splitted = word.split("\\|");
        System.out.println(Arrays.toString(splitted)); /* prints: [abc, def] */
    }
}

Comments

2

An alternate suggestion is to use Pattern.quote("|").

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.