加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 04:31:45 所属栏目:Java 来源:网络整理
导读:我正在开发一个项目,我的API在其结尾处返回带有id的url,我想将其解压缩以用于另一个函数.这是url的示例: String advertiserUrl = http://../../.../uuid/advertisers/4 this is the ID i want to extract. 目前我正在使用java的字符串函数substring(),但这
我正在开发一个项目,我的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中的P.suuid也可能在长度上有所不同

解决方法

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

使用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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读