【问题标题】:Separating the words after the last integer in a large String分隔大字符串中最后一个整数之后的单词
【发布时间】:2013-10-07 00:15:40
【问题描述】:
我见过很多人为了得到字符串的最后一个单词而做类似的事情:
String test = "This is a sentence";
String lastWord = test.substring(test.lastIndexOf(" ")+1);
我想做类似的事情,但是在最后一个 int 之后获取最后几个单词,它不能被硬编码,因为数字可以是任何东西,最后一个 int 之后的单词数量也可以是无限的。我想知道是否有一种简单的方法可以做到这一点,因为我想避免再次使用模式和匹配器,因为之前在此方法中使用它们以获得类似的效果。
提前致谢。
【问题讨论】:
标签:
android
regex
string
substring
lastindexof
【解决方案1】:
我想得到最后一个 int 之后的最后几个单词......因为数字可以是任何数字,最后一个 int 之后的单词数量也可以是无限的。
这是一个可能的建议。使用 Array#split
String str = "This is 1 and 2 and 3 some more words .... foo bar baz";
String[] parts = str.split("\\d+(?!.*\\d)\\s+");
现在parts[1] 保存字符串中最后一个数字之后的所有单词。
some more words .... foo bar baz
【解决方案2】:
这个呢:
String test = "a string with a large number 1312398741 and some words";
String[] parts = test.split();
for (int i = 1; i < parts.length; i++)
{
try
{
Integer.parseInt(parts[i])
}
catch (Exception e)
{
// this part is not a number, so lets go on...
continue;
}
// when parsing succeeds, the number was reached and continue has
// not been called. Everything behind 'i' is what you are looking for
// DO YOUR STUFF with parts[i+1] to parts[parts.length] here
}