【发布时间】:2019-02-25 11:28:27
【问题描述】:
我需要在斜线“/”之后获取某个字符串值,但我遇到了麻烦,因为字符串的格式值并不总是相同。
字符串的值为ff:
String raw = "Announcements/announcement_id)";
我需要的只是 announcement_id,可以使用lastIndexOf("/")+1 获得,但这并不总是字符串的格式,它也可能是这样的。
String raw = "Announcements/announcement_id/Comments/comment_id)";
我只需要 announcement_id 和 comment_id。
最后一部分的字符串值也可以是这样的。
String raw = "Announcements/announcement_id/Comments/comment_id/Replies/reply_id)";
我只需要 comment_id 和 reply_id。
我如何像使用 if else 语句一样正确地做到这一点。
if(has only one slash)
use lastIndexOf("/")+1 to get the id
else if (has three or more slashes)
get the value after second to the last forward slash and last forward slash
【问题讨论】:
-
使用 String.split("/") 并检查返回数组的长度
-
为什么在上一个例子中没有
announcement_id?我认为一个正则表达式会起作用 -
@XtremeBaumer 我现在不需要announcement_id
-
这样的话,Stultuske的想法就是你所需要的