【问题标题】:grab last four digits approach after deleting non digits using regex使用正则表达式删除非数字后抓取最后四位数字
【发布时间】:2020-05-26 21:34:52
【问题描述】:

我从 HTTP 响应标头获取下面显示的 URL(http://localhost:8080/CompanyServices/api/creators/2173),我想在 creators 之后获取 id,即 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);  
        } 

}

【问题讨论】:

  • 使用:(?<=creators/)\d+
  • 使用String id = str.replaceFirst("^.*?(\\d+)$", "$1");
  • @Andreas 你能解释一下String id = str.replaceFirst("^.*?(\\d+)$", "$1"); 吗?这行得通。

标签: java regex


【解决方案1】:

您可以使用正则表达式 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

[更新]

合并comment by Andreas如下:

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()) {
            value = Integer.parseInt(matcher.group(1));
        }
        System.out.println(value);
    }
}

输出:

2173

【讨论】:

  • "(creators/\\d+)" 更改为"creators/(\\d+)",这样您就不必这样做不必要的split("/")
猜你喜欢
  • 1970-01-01
  • 2014-10-21
  • 1970-01-01
  • 2023-01-18
  • 2020-09-29
  • 1970-01-01
  • 2017-08-29
  • 1970-01-01
  • 2013-04-28
相关资源
最近更新 更多