简体   繁体   中英

Regular expression to replace a value in query parameter

I get a query string from url by saying request.queryString() as -

supplyId=123456789b&search=true

I want to replace the value for "supplyId" with a new value. "supplyId" can come at any position in the query string. What would be the possible regular expression for this?

I wouldn't actually use regex for this, but string manipulation. Search for the position of "supplyId=" in the URL, then grab everything until the end of the string or "&", whichever comes first.

If you have to use a regex, try one of these:

(?<=supplyId=)[^&]+

supplyId=([^&]+)

Make sure case sensitivity is off. If you use the second pattern, the value you want will be in capture group 1.

I think you should be able to do something like so:

String queryString = "supplyId=123456789b&search=true";
String anyStringIlike = "someValueIlike";
String newQueryString = queryString.replaceAll("supplyId=[^&]+","supplyId=" + anyStringIlike);
System.out.println(queryString);
System.out.println(newQueryString);

This should print:

supplyId=123456789b&search=true

supplyId=someValueIlike&search=true

In perl you could do something like this.

perl -le '@m = ( "garbare=i123123123asdlfkjsaf&supplyId=123456789b&search=true" =~ /supplyId=(\\d+\\w+)&/g ); print for @m

public static String updateQueryString (String queryString, String name, String value) {
if (queryString != null) {
      queryString = queryString.replaceAll(name + "=.*?($|&)", "").replaceFirst("&$", "");
   }
 return addParameter(queryString, name, value);
}

public static String addParameter(queryString, name, value) {      
  return StringUtils.isEmpty(queryString) ? (name + "=" + value) : (queryString + "&" + name + "=" + value);

}

You call like: updateQueryString("supplyId=123456789b&search=true", "supplyId", "newValue");

output: search=true&supplyId=newValue

public class TestQueryStringValReplace {    
   public static String replace(String queryString, String propName, String newVal) {
       return queryString.replaceAll(propName+"=[^&]+", propName+"=" + newVal);
   }

   public static void main(String[] args) {
       Assert.assertEquals("supplyId=newVal&search=true", replace("supplyId=oldVal&search=true", "supplyId","newVal"));
       Assert.assertEquals("supplyId=newVal", replace("supplyId=oldVal", "supplyId","newVal"));
       Assert.assertEquals("search=true&supplyId=newVal&3rdprop=val", replace("search=true&supplyId=oldVal&3rdprop=val", "supplyId","newVal"));
   }

}

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