Split a string with two special characters

I have a string value that looks like this:

TE\;R20\;T11\;19

I would like to be divided into TE, R20, T11and 19. I am trying to apply a method to it split, but unfortunately it still cannot correctly split the string

Here is my source code

String description1 = CSVdata2[7];
System.out.println("The description1 is :"+description1);
String email1 = CSVdata2[2];
String [] data1 = description1.split(";");
String ID1 = data1[0];
String [] data2 = SysID1.split("/");
String ID2 = data2[0];
System.out.println("The ID2 is :"+ID2);

Here is my output file

The description1 is :TE\;R20\;T11\;19
The ID2 is :TE\

I tried to find some kind of approach on the Internet, but I still cannot make it split into the string I want

+4
source share
4 answers

You need to avoid \, because String \has an escape character. Try entering the code:

    String s = "TE\\;R20\\;T11\\;19";
String arr[] = s.split("\\\\;");
    System.out.println(Arrays.toString(arr));

To exit \, you need to use\

OP:

[TE, R20, T11, 19]
+2
source
    String test = "TE\\;R20\\;T11\\;19";
    System.out.println(test);
    for(String sub : test.split("\\\\;"))
    {
        System.out.println(sub);
    }

:
TE \; R20 \; T11 \; 19
TE
R20
T11
19

. String.split , .

+1
public static void main(String[] args) {
    String name="TE\\;R20\\;T11\\;19";
    String a[]=name.split("\\\\;");
    for(int i=0;i<a.length;i++){
        System.out.print(a[i]+" ");
    }
}
0
source

Using "Pattern.quote", we can split the string

String separator = "\\;";
String value = "TE\\;R20\\;T11\\;19";
String[] arrValues = value.split(Pattern.quote(separator));

 System.out.println(Arrays.asList(arrValues));

Output:

[TE, R20, T11, 19]

0
source

Source: https://habr.com/ru/post/1692397/


All Articles