繁体   English   中英

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

[英]How to trim/cut string in java by symbol?

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

 String advertiserUrl = http://../../.../uuid/advertisers/4 <<< this is the ID i want to extract.

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

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

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

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

您不需要为此使用正则表达式。

使用String#lastIndexOfsubstring代替:

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

您可以在斜杠上拆分字符串并获取返回的数组的最后位置,或使用lastIndexOf(“/”)获取最后一个斜杠的索引,然后对字符串的其余部分进行子串。

使用lastIndexOf()方法,该方法返回指定字符最后一次出现的索引。

String id = advertiserUrl.substring(advertiserUrl.lastIndexOf('/') + 1, advertiserUrl.length());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM