我正在开发一个项目,我的 API 返回末尾带有 id 的 url,我想提取它以用于另一个函数。这是示例网址:
String advertiserUrl = http://../../.../uuid/advertisers/4 <<< this is the ID i want to extract.
目前我正在使用名为 substring() 的 java 字符串函数,但这不是最佳方法,因为 ID 可能变成 3 位数字,而我只能得到其中的一部分。这是我目前的方法:
String id = advertiserUrl.substring(advertiserUrl.length()-1,advertiserUrl.length());
System.out.println(id) //4
它在这种情况下有效,但如果 id 是例如“123”,我只会在使用子字符串后将其作为“3”,所以我的问题是:有没有办法使用破折号“/”剪切/修剪字符串?可以说我当前的 url 中有 5/这样字符串会在检测到第五个破折号后被切断吗?此外,任何其他明智的方法也会有所帮助。谢谢。
P.s uuid in url 的长度也可能不同
最佳答案
您不需要为此使用正则表达式。
使用 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/advertisers/9";
// | preceded by "/"
// | | any non-"/" character, reluctantly quantified
// | | | followed by "/advertisers"
Pattern p = Pattern.compile("(?<=/)[^/]+?(?=/advertisers)");
Matcher m = p.matcher(advertiserUrl);
if (m.find()) {
System.out.println(m.group());
}
输出
2f5d1a31-878a-438b-a03b-e9f51076074a
关于java - 如何按符号修剪/剪切java中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34720098/