Wednesday, 15 April 2015

java - Regex for replacing two strings in the same line -



java - Regex for replacing two strings in the same line -

for illustration have 1 line in text file

additional_cost_utilities=(out.utilities.ener.steam_cons.value*0.056 + out.utilities.ener.elec_cons.value*0.09 + (string_new1*string_new2*0.003));

i need regex replace tokens of string_new1 , string_new2 new strings. regex utilize nil else edited in line other these 2 strings?

edit: strings replaced different each time. cant utilize replace. stable regex required modify string_new1 , string_new2 tokens independently of content, float numbers

the code trying utilize replace strings in specific line of big coding part following. regex needs recognize line , tokens of strings replaced. hope helps

try { path path = paths.get("read.m"); charset charset = standardcharsets.utf_8; string content = new string(files.readallbytes(path), charset); content = content.replace("string_1_in_the_line", "new string1") .replace("string_2_in_the_line", "new string2"); files.write(path, content.getbytes(charset)); } grab (ioexception e) { //simple exception handling, replace what's necessary utilize case! throw new runtimeexception("generating file failed", e); }

you don't need regex , read line string variable , phone call string.replace() method first param old string , , sec param new one. if want replace illustration string_new1 explicite string value rty :

string data="additional_cost_utilities=(out.utilities.ener.steam_cons.value*0.056 + out.utilities.ener.elec_cons.value*0.09 + (string_new1*string_new2*0.003));" data=data.replace("string_new1","\"a new string value\"");

java regex replace

No comments:

Post a Comment