简体   繁体   English

使用正则表达式检查URL是否包含任何参数

[英]Check whether a URL contains any parameter or not using a regular expression

How do I check whether any URL contains one or more parameters or not? 如何检查是否有任何URL包含一个或多个参数?

For example, if the URL is 例如,如果URL是

.../PaymentGatewayManager?mode=5015

then we should be able to know that URL contains one parameter. 那么我们应该能够知道URL包含一个参数。 Or if the URL is 或者如果URL是

.../PaymentGatewayManager

then we should be able to know that the URL does not contain any parameter. 那么我们应该能够知道URL不包含任何参数。 Or if the URL is 或者如果URL是

.../PaymentGatewayManager?mode=5015&test=456123&abc=78

then we should be able to know that the URL contains three parameters, and we should also be able to know the parameter name and values of that using any regular expression in Java. 然后我们应该能够知道URL包含三个参数,并且我们还应该能够使用Java中的任何正则表达式知道参数名称和值。

If you wanted to do it with a regular expression (this can be optimized as well to do a search inside a group): 如果你想用正则表达式做(这也可以优化以在组内进行搜索):

public static void main(String[] args) {
    String input = ".../PaymentGatewayManager?mode=5015&test=456123&test2=SomeRandomValue&abc=78";
    if(input.contains("?")){
        System.out.println("It does contain parameters");
        input = "&" + input.substring(input.indexOf("?")+1) + "&";

        System.out.println(input);

        Pattern p = Pattern.compile("&?(\\w.+?)=(.+?)&");
        Matcher m = p.matcher(input);

        while(m.find()){
            System.out.println("Token ->" + m.group(1));
            System.out.println("Value ->" + m.group(2));
        }
    }
}

Use the methods of java.net.URI to get everything about an URL. 使用java.net.URI的方法获取有关URL的所有信息。

Edit: Use URI, not URL (thanks McDowell). 编辑:使用URI,而不是URL(感谢McDowell)。

You can String.split() the URL, or tokenize it using java.util.StringTokenizer , using ? 您可以使用String.split() URL,或使用java.util.StringTokenizer对其进行标记,使用? as the splitter character. 作为分裂者角色。 If you get more than one pieces, then it's sure that the URL contains parameters. 如果您获得多个部分,则确保该URL包含参数。

To get the parameters, split the second part by & in the same way. 要获取参数,通过分割第二部分&以同样的方式。 You'll get the parameters. 你会得到参数。 Splitting each one of them by = will give you the names and values. 将每一个拆分为=将为您提供名称和值。

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

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