简体   繁体   English

Java用正则表达式拆分字符串

[英]java split string with regular expression

I have a string like "~~banana~apple~". 我有一个字符串,例如“ ~~香蕉〜苹果〜”。 I want to split that string with "~" is seperator and i want last element in the array after split is "" not "apple". 我想用“〜”分割该字符串,是分隔符,并且我希望分割后数组中的最后一个元素是“”而不是“ apple”。

        String fruits = "~~banana~apple~";
        String[] arr = fruits.split("~");
        String last = "";  //Last string i need
        if (arr.length > 0 )
            last =  arr[arr.length-1];

        System.out.println("last: " + last);

//The result //结果

last: apple 上一个:苹果

//but i want in this case the value of last must be "" because afer "apple" have "~". //但是在这种情况下,我希望last的值必须为“”,因为“ apple”之后为“〜”。

Sorry my bad english. 对不起,我的英语不好。

I'm guessing that you are looking for split("~",-1) . 我猜您正在寻找split("~",-1) By default split removes empty strings ( "" ) from the end, but with negative limit it will leave them. 默认情况下, split从末尾删除空字符串( "" ),但是如果设置为负数,它将保留它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM