dynamic - Replace string dynamically using Regex in java code -


i want solution below in java code

string inputstr = "this sample @hostname1 @host-name2 want convert string :@test host-@test1 format i.e dollar followed open braces, string , close braces.";

output string need

output: "this sample ${hostname1} ${host-name2} want convert string :${test} host-${test1} format i.e dollar followed open braces, string , close braces.";

i tried below like

public void regex(string intputstr){         string pattern = "\\s(@)\\s+";          pattern r = pattern.compile(pattern);          matcher m = r.matcher(commands);           string replacepattern = " \\$\\{\\s+\\} ";          int i=0;           while(m.find()) {              pattern.compile(pattern).matcher(intputstr).replaceall(replacepattern);             // system.out.println(m.group(i));              //i++;          }            // system.out.println(i);         system.out.println(intputstr);     } 

but exceptions , not able proceed. please help.

you can away following one-liner:

inputstr = inputstr.replaceall("@(.*?)\\s", "\\${$1} "); 

this matches regex @(.*?)\\s, captures between @ symbol , nearest space, , replaces formatting want.

string inputstr = "this sample @hostname1 @host-name2 want convert string :@test host-@test1 format i.e dollar followed open braces, string , close braces."; // add space match term should occur last word inputstr += " "; inputstr = inputstr.replaceall("@(.*?)\\s", "\\${$1} "); inputstr = inputstr.substring(0, inputstr.length()-1);  system.out.println(inputstr); 

output:

this sample ${hostname1} ${host-name2} want convert string :${test} host-${test1} format i.e dollar followed open braces, string , close braces. 

Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

java - How to resolve The method toString() in the type Object is not applicable for the arguments (InputStream) -