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 \|
does the same thing too.
I tried using \\|
, but that just gives me: Invalid escape sequence (valid ones are \\b \\t \\n \\f \\r \\" \\' \\\\ )
.
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.
另一个建议是使用Pattern.quote("|")
。
Escape the backslash. You are in a Java string, and it should contain a literal backslash.
"\\|"
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] */
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.