[英]Obtaining a substring value for a delimited String of unknown length
Given the String data, delimited by :
and comma separated给定字符串数据,由
:
和逗号分隔
String times = 6:10000:first,12:12000:second,18:15000:third
I need to get the third value from the last comma separated list, in this above case 15000
我需要从最后一个逗号分隔列表中获取第三个值,在上面的例子中是
15000
Or 20000
in the below case或者在以下情况下为
20000
String times = 6:10000:first,12:12000:second,18:15000:third,24:20000:fourth
Or 30000
in the below case或者在以下情况下为
30000
String times =
6:10000:first,12:12000:second,18:15000:third,24:20000:fourth,30:30000:fourth
Something like:就像是:
public String getLastTimeFromCommaSeparatedList() {
return times.substring(mileages.lastIndexOf(':') + 2);
}
I'm unclear how I can get the value I need, given the comma separated list is of an unknown length.鉴于逗号分隔列表的长度未知,我不清楚如何获得所需的值。
You can use substring with lastIndexOf and split like this:您可以将 substring 与 lastIndexOf 一起使用并像这样拆分:
times.substring(time.lastIndexOf(",")).split(":")[1]
Demo演示
String[] times = {"6:10000:first,12:12000:second,18:15000:third",
"6:10000:first,12:12000:second,18:15000:third,24:20000:fourth",
"6:10000:first,12:12000:second,18:15000:third,24:20000:fourth,30:30000:fourth"
};
for (String time : times) {
System.out.println(
time.substring(time.lastIndexOf(",")).split(":")[1]
);
}
Outputs产出
15000
20000
30000
You can use regular expression .您可以使用正则表达式。
String times = "6:10000:first,12:12000:second,18:15000:third,24:20000:fourth,30:30000:fourth";
java.util.regex.Pattern pttrn = java.util.regex.Pattern.compile("(\\d+):[a-z]+$");
java.util.regex.Matcher mtchr = pttrn.matcher(times);
if (mtchr.find()) {
System.out.println(mtchr.group(1));
}
else {
System.out.println("Nothing found.");
}
Explanation of the pattern图案的解释
(\\d+)
a string of one or more digits. (\\d+)
一个或多个数字的字符串。:
the colon character :
冒号字符[az]+
one or more lowercase letters [az]+
一个或多个小写字母$
the end of the input string $
输入字符串的结尾So the pattern looks for digits followed by a colon followed by lowercase letters at the end of the input string.因此,该模式在输入字符串的末尾查找数字后跟冒号后跟小写字母。 It also groups the digits.
它还对数字进行分组。
It works for every sample string in your question.它适用于您问题中的每个示例字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.