Reputation: 1277
I have a string in the format like "test\00216243". I need to split the string in Java based on the backslash '\' .
My Program:
public class StringTest {
public static void main(String[] args) {
String taskOwner = "test\00216243";
String taskArray[] = taskOwner.split(Pattern.quote(System.getProperty("file.separator")));
System.out.println(taskArray[0]);
}
}
When i run this program i am getting the following result but not the result as 'test'. Any help?
Result:
test16243
Upvotes: 0
Views: 6031
Reputation: 26077
Just to add on
\
is a special character in regular expressions, as well as in Java string literals. If you want a literal backslash in a regex, you have to double it twice.
When you type "\\"
, this is actually a single backslash (due to escaping special characters in Java Strings).
Regular expressions also use backslash as special character, and you need to escape it with another backslash. So in the end, you need to pass "\\" as pattern to match a single backslash.
public static void main(String[] args) {
String taskOwner = "test\\00216243";
String taskArray[] = taskOwner.split("\\\\");
System.out.println(taskArray[0]);
}
output
test
00216243
Upvotes: 4
Reputation: 636
String "test\00216243"
should be replaced with "test\\00216243"
Because \
represent the escape sequence, you need to use \\
in the string to represent a \
Try this
public static void main(String[] args) {
String taskOwner = "test\\00216243";
String myarray[] = taskOwner.split("\\\\");
System.out.println(myarray[0]+" "+myarray[1]);
}
Output
test 00216243
Reference:
How to split a java string at backslash
Upvotes: 0
Reputation: 174716
\002
represents a unicode character. SO i suggest you to split your input according to the character other than alphabet or digit.
String string1 = "test\00216243";
String part[] = string1.split("[^a-z0-9]");
System.out.println(part[0]);
Output:
test
Upvotes: 2