I am no friend of questions without any code but I have absolutely no idea how to search for this issue.
I got a String like this with a couple of key/value pairs: test=39&test2=4&test3=10
and an update String like test2=5
now I want to call the String.replaceAll
method with an expression that replaces the above String with test2=5
so I get test=39&test2=5&test3=10
String lTest = "test=39&test2=4&test3=10";
String lUpdate = "test2=5";
Assert.assertEquals("test=39&test2=5&test3=10",lTest.replace(lTest,???regex???);
lUpdate
can be test
or test2
or test3
. the value behind the = can be a number between 0 and 1000.
How can I manage this with regular expression?
Thx a lot for your help.
UPDATE!!! this works like a charme(thx to user laune):
@Test
public void test(){
String lResult = update("test1=1234&test2=4949&test3=1", "test2=42");
assertEquals("test1=1234&test2=42&test3=1", lResult);
lResult = update("test1=1234&test2=4949&test3=1", "test3=5");
assertEquals("test1=1234&test2=4949&test3=5", lResult);
lResult = update("test1=1234&test2=4949&test3=1", "test1=100");
assertEquals("test1=100&test2=4949&test3=1", lResult);
}
static String update(String str, String upd) {
// split to get the keyword and the value
String[] kwv = upd.split("=");
// compose the regex
String regex = "(?<=^|&)" + Pattern.quote(kwv[0]) + "=\\d+";
return str.replaceAll(regex, upd);
}