如何在Java中按符号截取字符串?

3
我正在处理一个项目,我的 API 返回带有 id 结尾的 url,我想提取它以在另一个函数中使用。这是一个示例 url:
 String advertiserUrl = http://../../.../uuid/advertisers/4 <<< this is the ID i want to extract.

目前我正在使用Java的字符串函数substring(),但这并不是最好的方法,因为ID可能会变成三位数,那么我只能得到其中的一部分。以下是我的当前方法:

String id = advertiserUrl.substring(advertiserUrl.length()-1,advertiserUrl.length());
System.out.println(id) //4

在这种情况下它是有效的,但如果ID是例如"123",那么在使用子字符串后我只会得到它作为"3",所以我的问题是:是否有一种使用破折号"/"来剪切/修整字符串的方法?假设在我的当前网址中有5个/,因此在检测到第五个破折号之后字符串将被截断?此外,任何其他明智的方法也将有所帮助。谢谢。
附:URL中的UUID长度可能也会有所不同。
3个回答

5
您不需要使用正则表达式来实现这个功能。
相反,可以使用String#lastIndexOf方法和substring方法来实现:
String advertiserUrl = "http://../../.../uuid/advertisers/4";// <<< this is the ID i want to extract.
// this implies your URLs always end with "/[some value of undefined length]". 
// Other formats might throw exception or yield unexpected results
System.out.println(advertiserUrl.substring(advertiserUrl.lastIndexOf("/") + 1));

输出

4

更新

要找到uuid值,您可以使用正则表达式:

String advertiserUrl = "http://111.111.11.111:1111/api/ppppp/2f5d1a31-878a-438b-a03b-e9f51076074a/adver‌​tisers/9";
//                           | preceded by "/"
//                           |     | any non-"/" character, reluctantly quantified
//                           |     |     | followed by "/advertisers"
Pattern p = Pattern.compile("(?<=/)[^/]+?(?=/adver‌​tisers)");
Matcher m = p.matcher(advertiserUrl);
if (m.find()) {
    System.out.println(m.group());
}

输出

2f5d1a31-878a-438b-a03b-e9f51076074a


谢谢!解决了我的问题。 - Tomas
如果我想从同一个URL中提取uuid怎么办?我该如何实现?@Mena - Tomas
1
@Tomas 可能有一些空白的地方 - 对于给定的 URL,它对我也不起作用,然后我重写了它,完全相同的代码就可以工作了。尝试再次复制模式初始化。还要确保使用 if 条件来检查是否匹配,否则会出现 IllegalStateException - Mena
谢谢你的帮助,我不得不重写这个正则表达式,最终的解决方案是:"[^/.]+(?=/advertisers)" - Tomas
@Tomas 不用谢。你说的可以省略后顾组,但在我的情况下似乎也能正常工作。 - Mena
显示剩余2条评论

1
您可以将字符串根据斜杠分割并获取返回数组的最后一个位置,或者使用lastIndexOf("/")获取最后一个斜杠的索引,然后截取字符串的其余部分。

1
使用lastIndexOf()方法,该方法返回指定字符的最后一次出现的索引。
String id = advertiserUrl.substring(advertiserUrl.lastIndexOf('/') + 1, advertiserUrl.length());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接