【问题标题】:Getting specific value from url query string using Regex in Java在 Java 中使用 Regex 从 url 查询字符串中获取特定值
【发布时间】:2014-02-18 15:00:47
【问题描述】:

我有一个字符串,其 url 如下:http://www.website.com/search?productId=1500

如何通过正则表达式获取productId的值?

【问题讨论】:

  • 尝试使用捕获组。
  • 你有什么特别的理由使用正则表达式吗?如果没有,您可以使用java.net.URLgetQuery() 函数和字符串拆分。

标签: java regex


【解决方案1】:

我可能会使用 Appache Commons 的 URLEncodedUtils

String url = "http://www.website.com/search?productId=1500";

List<NameValuePair> paramsList = URLEncodedUtils.parse(new URI(url),"utf-8");
for (NameValuePair parameter : paramsList)
    if (parameter.getName().equals("productId"))
        System.out.println(parameter.getValue());

输出1500.

但是如果你真的想用正则表达式你可以试试

Pattern p = Pattern.compile("[?&]productId=(\\d+)");
Matcher m = p.matcher(url); //  _____________↑ group 1
if (m.find())               // |
    System.out.println(m.group(1));

【讨论】:

    【解决方案2】:

    如果你真的想这样做:

    public static void main(String[] args) throws Exception {
        Pattern pattern = Pattern.compile("http://www.website.com/search\\?productId=(\\d+)");
        Matcher matcher = pattern.matcher("http://www.website.com/search?productId=1500");
        if (matcher.matches()) {
            String productId = matcher.group(1);
        }
    }
    

    但是,有一些库可以解析 URL 查询参数,它们还会执行 URL 解码参数等操作。正则表达式无法做到这一点。

    这是一个关于 SO 的问题,它解释了如何使用库甚至代码 sn-p 来正确解析来自 URL 的查询字符串参数:Parse a URI String into Name-Value Collection

    【讨论】:

      【解决方案3】:

      如果您知道所需号码以productId= 为前缀,那么为什么不使用substring

      【讨论】:

        猜你喜欢
        • 2012-04-24
        • 1970-01-01
        • 2013-03-10
        • 1970-01-01
        • 1970-01-01
        • 2013-06-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多