简体   繁体   中英

How to get the last token from the string split by a pattern

I am having a string

String S1="Hello@world@today@2018/01/01"
S2="Foo@Obj@new@tornado"

I want to get the last token always from each of these strings. Eg: 2018/01/01 in S1 and tornado in S2.

Please help.

If @ is a common delimiter you could do

String[] parts = S1.split("@");
final String lastItem = parts[parts.length - 1];

Or, perhaps an easier way of doing it depending on your preference:

final String lastItem = S1.substring(S1.lastIndexOf("@"));

You can use following function on String object for which you want last token

 public static String getTocken(String s) {
    String []str=s.split("@");
    return str[str.length-1];
}

Pass the input String and get the result.

use regex and replaceAll

.*@


S1.replaceAll(".*@", "");
S2.replaceAll(".*@", "");

output

2018/01/01
tornado

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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