如何用符号修剪/剪切java中的字符串?

Tom*_*mas 3 java regex string

我正在开发一个项目,我的API在其结尾处返回带有id的url,我想将其解压缩以用于另一个函数.这是url的示例:

 String advertiserUrl = http://../../.../uuid/advertisers/4 <<< this is the ID i want to extract.
Run Code Online (Sandbox Code Playgroud)

目前我正在使用java的字符串函数substring(),但这不是最好的方法,因为ID可能会成为3位数字,我只会得到它的一部分.继承了我目前的做法:

String id = advertiserUrl.substring(advertiserUrl.length()-1,advertiserUrl.length());
System.out.println(id) //4
Run Code Online (Sandbox Code Playgroud)

它适用于这种情况,但如果id是例如"123",我只会在使用子字符串后得到它为"3",所以我的问题是:有没有办法用破折号"/"剪切/修剪字符串?让我说当前网址中的theres 5 /所以字符串在检测到第五个破折号后会被切断?任何其他合理的方法也会有所帮助.谢谢.

url中的ps uuid也可能在长度上有所不同

Men*_*ena 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));
Run Code Online (Sandbox Code Playgroud)

产量

4
Run Code Online (Sandbox Code Playgroud)

更新

要查找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());
}
Run Code Online (Sandbox Code Playgroud)

产量

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