我正在从HTTP响应标头中获得下面显示的URL(http://localhost:8080/CompanyServices/api/creators/2173
),我想在id
后面的creators
之后获得2173
。
因此,我删除了所有非数字,如下所示,并得到以下结果:80802173
。从上述数字集中获取最后4位数字是一种好方法吗?
有一件事,根据我部署应用程序的服务器,这部分localhost:8080
可能会发生变化,所以我想知道是否应该在creators/
之后抢些东西?如果是,那么最好的解决方法是什么?
public class GetLastFourIDs {
public static void main(String args[]){
String str = "http://localhost:8080/CompanyServices/api/creators/2173";
String replaceString=str.replaceAll("\\D+","");
System.out.println(replaceString);
}
}
例如,您可以使用regex API
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String str = "http://localhost:8080/CompanyServices/api/creators/2173";
Pattern pattern = Pattern.compile("(creators/\\d+)");
Matcher matcher = pattern.matcher(str);
int value = 0;
if (matcher.find()) {
// Get e.g. `creators/2173` and split it on `/` then parse the second value to int
value = Integer.parseInt(matcher.group().split("/")[1]);
}
System.out.println(value);
}
}
输出:
2173
非正则表达式解决方案:
public class Main {
public static void main(String[] args) {
String str = "http://localhost:8080/CompanyServices/api/creators/2173";
int index = str.indexOf("creators/");
int value = 0;
if (index != -1) {
value = Integer.parseInt(str.substring(index + "creators/".length()));
}
System.out.println(value);
}
}
输出:
2173