Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to replace a value in query parameter

Tags:

java

regex

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?

like image 732
Saurabh Avatar asked May 17 '12 19:05

Saurabh


3 Answers

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.

like image 179
Justin Morgan Avatar answered Oct 27 '22 19:10

Justin Morgan


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

like image 5
npinti Avatar answered Oct 27 '22 21:10

npinti


In perl you could do something like this.

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

like image 2
Dhawan Gayash Avatar answered Oct 27 '22 20:10

Dhawan Gayash