How to replace a particular string with value in java -
edit :
goal : http://localhost:8080/api/upload/form/test/test
is possible have thing `{a-b, a-b..0-9}` kind of pattern , match them , replace value. i have following string
http://localhost:8080/api/upload/form/{uploadtype}/{uploadname} there can no of strings {uploadtype}/{uploadname}.
how replace them values in java?
[edited] apparently don't know substitutions you'll looking for, or don't have reasonable finite map of them. in case:
pattern subst_patt = pattern.compile("\\{(\\w+)\\}"); stringbuilder sb = new stringbuilder( template); matcher m = subst_patt.matcher( sb); int index = 0; while (m.find( index)) { string subst = m.group( 1); index = m.start(); // string replacement = "replacement"; // .. lookup subst -> replacement here sb.replace( index, m.end(), replacement); index = index + replacement.length(); } look, i'm expecting +1 now.
[simpler approach] string.replace() 'simple replace' & easy use purposes; if want regexes can use string.replaceall().
for multiple dynamic replacements:
public string substitutestr (string template, map<string,string> substs) { string result = template; (map.entry<string,string> subst : substs.entryset()) { string pattern = "{"+subst.getkey()+"}"; result = result.replace( pattern, subst.getvalue()); } return result; } that's quick & easy approach, start with.
Comments
Post a Comment