Reputation: 55
I am trying to split the below String based on backslash"\" but unable to achieve this for mar\12\2013
String s1 = "mar\12\2013";
String[] s =s1.split("\\\\");
for(String s2 : s){
System.out.println(s2);
}
Upvotes: 1
Views: 124
Reputation: 4463
In Java "mar\12\2013"
is an invalid string.
To use mar\12\2013
in Java, you need "mar\\12\\2013"
.
If you are taking input from user as "mar\12\2013"
, then also you have to split it with \\\\
.
Reason : .split()
takes regex
as a parameter.
\
in regex, we need \\
, because \
is an escape character in regex
.Also, \
is an escape character in Java, so we need to escape both \
of \\
, which makes it \\\\
.
String s1= //take input from user // "mar\12\2013"
String[]s=s1.split("\\\\");
for(String s2:s) {
System.out.println(s2);
}
The above code will work the way you wish.
See the working code here.
Upvotes: 1
Reputation: 13552
See the below code it worked fine for me
public class StringTest {
public static void main(String arg[]){
String s1="mar\\12\\2013";
String[]s=s1.split("\\");
for(String s2:s){
System.out.println(s2);
}
}
}
Upvotes: 0
Reputation: 1403
String s1="mar\12\2013";
String[]s=s1.split("\\");
for(String s2:s){
System.out.println(s2);
}
You doubled up the selectors, i cant actually test atm but i believe it just needs the 2, the first escaping the second.
Upvotes: 0