Reputation:
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 \" \' \\ )
.
Upvotes: 3
Views: 272
Reputation: 135762
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] */
}
}
Upvotes: 2
Reputation: 51501
Escape the backslash. You are in a Java string, and it should contain a literal backslash.
"\\|"
Upvotes: 2
Reputation: 21760
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.
Upvotes: 6