I have a string and want to replace certain charactes in it.
Input String = "abc test=0 test1=123 test2=764"
Output String = "abc test=$test test1=$test1 test2=$test2"
I have tried couple of things using replace and replaceAll in java. For example :
String abc = directiveValue.replaceAll("test%", test "=$" test);
or
String abc = directiveValue.replaceAll("test[.*]", test "=$" test);
CodePudding user response:
You could match:
(test\d*)=\S*
And replace with the dollar sign between the 2 capture groups $1=\$$1
System.out.println(
"abc test=0 test1=123 test2=764"
.replaceAll(
"(test\\d*)=\\S*",
"$1=\\$$1"
)
);
Output
abc test=$test test1=$test1 test2=$test2
CodePudding user response:
We can use a regex replacement:
String input = "abc test=0 test1=123 test2=764";
String output = input.replaceAll("(\\w )=\\w ", "$1=\\$$1");
System.out.println(output);
// abc test=$test test1=$test1 test2=$test2
CodePudding user response:
Using VScode, I will use this (test)(\d?)(=)(\b. ?\b)
and replace with $1$2$3$test$2
I hope it inspires you with your java implementation. :)