Regular expression to replace value in query parameter

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

supplyId=123456789b&search=true

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

+3
source share
5 answers

I would not actually use regex for this, but string manipulation. Find the position "supplyId =" in the URL, then take everything to the end of the line or "&", whichever comes first.

If you need to use regex, try one of them:

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

supplyId=([^&]+)

, . , 1.

+4

, - :

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

:

supplyId = 123456789b & search = true

supplyId = someValueIlike & =

+3

In perl, you can do something like this.

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

+2
source
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: updateQueryString("supplyId=123456789b&search=true", "supplyId", "newValue");

conclusion: search=true&supplyId=newValue

+1
source
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"));
   }

}

0
source

All Articles