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

标签 java regex string

我正在开发一个项目,我的 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#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

关于java - 如何按符号修剪/剪切java中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34720098/

相关文章:

java - GAE 开始使用 Java,Eclipse Indigo - 无法编译为 1.6

regex - Htaccess 重定向 https 和 http 以及自定义 url

javascript - 如何返回与正则表达式匹配的JavaScript字符串的一部分?

python - 在python中将 '1/2'和str(1/2)传递给decimal.Decimal之间的区别

字符串.替换器 : how to replace all substrings at once?

java - 如何将选定目录中的文件放入arraylist Android studio

继承中的java异常处理

Java Servlet header 隐式对象

python - 正则表达式匹配引号中仅包含 3 个或更少大写单词的字符串

java - 如何将字符串转换为日期并保持格式正确