Raj Malhotra
Raj Malhotra

Reputation: 55

how to split string based on delimiter as "\"

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

Answers (3)

Shrinivas Shukla
Shrinivas Shukla

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.

  • To specify \ 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

Subodh Joshi
Subodh Joshi

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

Daniel Brose
Daniel Brose

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

Related Questions