I want to ask something about java regex and hope I will find some help here.
I have a string which looks like "textX|textY|textZ"
. Now I want to split this on each |
character in java.
I tried it with
string.split("\|");
but I just get a "Invalid escape sequence"
error.
How can I split the above string when I use |
as separator?
You need double escaping in Java so use:
String[] tokens = string.split("\\|")
OR else use character class:
String[] tokens = string.split("[|]");
you should use \\\\|
for escaping meta character.
In Java you need to escape characters twice for regex: once for the string, once for the regex.
Try
string.split("\\|")
You have to use double back slash \\\\
: string.split("\\\\|")
.
It is because back slash is a escape character for both: java and regex. First one escapses the second for java, so that the "real" backslash is passed to regex.
simply doing
string.split("\\|");
in java when we escape we do it by two backslashes
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.