gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 16:59:50 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com