java - 如何从字符串中的最后一个逗号获取最后一个单词

标签 java android

我想检索句子中最后一个分号之前的最后一个单词,请参阅以下内容。

String met = "This is the string with comma numberone; string having second wedaweda; last word";
String laststringa = met.substring(met.lastIndexOf(";")-1);
if(laststringa != null)
{
    System.out.println(laststringa);
}else{
    System.out.println("No Words");
}

我得到了奇怪的结果

a; last word

就我而言,对于上面的字符串,我应该得到 韦达韦达 最后一个分号之前的最后一个。

最佳答案

该字符是分号(不是逗号),调用 lastIndex() 会结束匹配,您需要再次调用 lastIndex() 开始比赛。比如,

String met = "This is the string with comma numberone; string having second wedaweda; last word";
int lastIndex = met.lastIndexOf(";");
int prevIndex = met.lastIndexOf(";", lastIndex - 1);
String laststringa = met.substring(prevIndex + 1, lastIndex).trim();
if (laststringa != null) {
    System.out.println(laststringa);
} else {
    System.out.println("No Words");
}

输出为

string having second wedaweda

要获取最后一个单词,您可以拆分 \\s+ (匹配一个或多个空白字符的正则表达式),例如

if (laststringa != null) {
    String[] arr = laststringa.split("\\s+");
    System.out.println(arr[arr.length - 1]);
} else {
    System.out.println("No Words");
}

哪个输出(请求的)

wedaweda

关于java - 如何从字符串中的最后一个逗号获取最后一个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28520856/

相关文章:

java - 为什么选择全局环境基金?我什么时候必须使用 GEF

光栅之外的 Java getSubimage()

java - Asynctask 中的基本适配器不起作用

android - OpenSL ES是否支持PerformanceMode::LowLatency?

android - 如何使用 6 个按钮创建布局,如 Windows 磁贴

java - 使用 IOUtils 和 ImageIO 写入图像文件有什么区别

java - Gradle:类路径资源[]无法解析为URL,因为它不存在

java - Rss Feed Java MVC

Android 浏览器自动调整文本大小

java - 有没有办法在 RecyclerView 下添加按钮或任何内容