How to extract parameters from a given url

后端 未结 7 572
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-27 05:10

In Java I have:

String params = \"depCity=PAR&roomType=D&depCity=NYC\";

I want to get values of depCity parameters (PA

7条回答
  •  攒了一身酷
    2020-11-27 05:50

    Not sure how you used find and group, but this works fine:

    String params = "depCity=PAR&roomType=D&depCity=NYC";
    
    try {
        Pattern p = Pattern.compile("depCity=([^&]+)");
        Matcher m = p.matcher(params);
        while (m.find()) {
            System.out.println(m.group());
        } 
    } catch (PatternSyntaxException ex) {
        // error handling
    }
    

    However, If you only want the values, not the key depCity= then you can either use m.group(1) or use a regex with lookarounds:

    Pattern p = Pattern.compile("(?<=depCity=).*?(?=&|$)");
    

    It works in the same Java code as above. It tries to find a start position right after depCity=. Then matches anything but as little as possible until it reaches a point facing & or end of input.

提交回复
热议问题