简体   繁体   中英

Replace design pattern in query string

I have currently some URL like this :

?param=value&offset=19&size=100

Or like that :

?offset=45&size=50&param=lol

And I would like to remove for each case the "offset" and the "value". I'm using the regex method but I don't understand how it's really working... Can you please help me for that? I also want to get both values of the offset and the size.

Here is my work...

\(?|&)offset=([0-9])[*]&size=([0-9])[*]\

But it doesn't works at all!

Thanks.

Assuming is Javascript & you only want to remove offset param:

str.replace(\offset=[0-9]*&?\,"")

For Java:

str=str.replaceAll("offset=[0-9]*&?","");
//to remove & and ? at the end in some cases
if (str.endsWith("?") || str.endsWith("&")) 
    str=str.substring(0,str.length()-1);

With out regex .

String queryString ="param=value&offset=19&size=100";
    String[] splitters = queryString.split("&");
    for (String str : splitters) {
        if (str.startsWith("offset")) {
            String offset = str.substring(str.indexOf('=') + 1);//like wise size also
            System.out.println(offset); //prints 19
        }
    } 

If you need to use a regular expression for this then try this string in java for the regular expression (replace with nothing):

"(?>(?<=\\?)|&)(?>value|offset)=.*?(?>(?=&)|$)"

It will remove any parameter in your URL that has the name 'offset' or 'value'. It will also conserve any required parameter tokens for other parameters in the URL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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