Home > Mobile >  Replace multiple substrings within a string
Replace multiple substrings within a string

Time:12-21

I have string such as

String url = "www.test.com/blabla/?p1=v1?p2=v2?p3=v3"

I would like to replace the "substrings" "v1","v2" and "v3" with other values. How can I achieve this?

CodePudding user response:

Does something like this work for your case?

String url = "www.test.com/blabla/?p1=v1?p2=v2?p3=v3";
    
String result = String.format(url.replaceAll("v[0-9]", "%s"), "arg1", "arg2", "arg3");
    
System.out.println(result); //www.test.com/blabla/?p1=arg1?p2=arg2?p3=arg3

Edit: Just a brief explanation of what this does, it replaces all the v1,v2,v3,v4,v5,v6,v7,v8,v9,v0 in the original url for %s and then uses this in the format method so you can attribute what you want it to be.

  • Related