使用正则表达式删除非数字后,获取最后四位数字的方法

问题描述 投票:0回答:1

我正在从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);  
        } 

}
java regex
1个回答
1
投票

例如,您可以使用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
© www.soinside.com 2019 - 2024. All rights reserved.