簡體   English   中英

拆分涉及兩個特殊字符的String

[英]Split the String involving two special character

我有一個字符串值,如下所示:

TE\;R20\;T11\;19

我想把它分成TER20T1119 我嘗試在它上應用split方法但不幸的是它仍然無法正確分割字符串

這是我的源代碼

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);

這是我的示例輸出

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

我嘗試在網上搜索一些方法,但我仍然不能將它分成我想要的字符串

你需要轉義\\因為在String \\是一個轉義字符。 試試以下代碼:

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

逃避\\你需要使用\\

OP:

[TE, R20, T11, 19]
    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方法接受正則表達式字符串而不是單個字符進行拆分。

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]+" ");
    }
}

通過使用"Pattern.quote"我們可以分割 字符串

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

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

輸出:

[TE,R20,T11,19]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM