简体   繁体   English

如何使用正则表达式获取此URL参数

[英]How can I get this URL parameter with regex

String url = "mysite.com/index.php?name=john&id=432"

How can I extract the id parameter (432)? 如何提取id参数(432)?

it can be in any position in the url and the length of the id varies too 它可以在url中的任何位置,并且id的长度也有所不同

You can use Apache URLEncodedUtils from HttpClient package: 您可以从HttpClient包中使用Apache URLEncodedUtils

import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import java.nio.charset.Charset;
import java.util.List;

public class UrlParsing {
    public static void main(String[] a){
        String url="http://mysite.com/index.php?name=john&id=42";
        List<NameValuePair> args= URLEncodedUtils.parse(url, Charset.defaultCharset());
        for (NameValuePair arg:args)
            if (arg.getName().equals("id"))
                System.out.println(arg.getValue());
    }
}

This print 42 to the console. 此打印42到控制台。

If you have the url stored in a URI object, you may find useful an overload of URLEncodedUtils.parse that accept directly an URI instance. 如果您将URL存储在URI对象中,则可能会发现有用的URLEncodedUtils.parse的重载可以直接接受URI实例。 If you use this overloaded version, you have to give the charset as a string: 如果使用此重载版本,则必须将字符集作为字符串提供:

URI uri = URI.create("http://mysite.com/index.php?name=john&id=42");
List<NameValuePair> args= URLEncodedUtils.parse(uri, "UTF-8");

I just give an abstract regex. 我只给出一个抽象的正则表达式。 add anything you don't want in id after [^& 加你不想在任何id[^&

Pattern pattern = Pattern.compile("id=([^&]*?)$|id=([^&]*?)&");

Matcher matcher = pattern.matcher(url);

if (matcher.matches()) {
    int idg1   = Integer.parseInt(matcher.group(1));
    int idg2   = Integer.parseInt(matcher.group(2));
}

either idg1 or idg2 has value. idg1idg2都有值。

您可以使用:

String id = url.replaceAll("^.*?(?:\\?|&)id=(\\d+)(?:&|$).*$", "$1");

The regex has already been given, but you can do it with some simple splitting too: 正则表达式已经给出,但是您也可以通过一些简单的拆分来实现:

public static String getId(String url) {
        String[] params = url.split("\\?");
        if(params.length==2) {
                String[] keyValuePairs = params[1].split("&");
                for(String kvp : keyValuePairs) {
                        String[] kv = kvp.split("=");
                        if(kv[0].equals("id")) {
                                return kv[1];
                        }
                }
        }
        throw new IllegalStateException("id not found");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM