Code:
record = record.replace("%icmp4-echo.*%","%\"icmp4-echo.*\"%");
record originally is:
%icmp4-echobalabalabalabala%
want to get replaced to:
%"icmp4-echobalabalabalabala"%
But my code does not work. Need some help or hint. thanks!
Use String#replaceAll():
String input = "%icmp4-echobalabalabalabala%";
input = input.replaceAll("%(icmp4-echo.*?)%", "%\"$1\"%");
Here, we match the pattern %(.*?)% and then replace that with %"$1"%. The quantity $1 is a capture group, equal to whatever is inside the parenthesis. As a side note, I made the capture group (.*?) non greedy, in case you want to replace multiple occurrences inside your string.
String#replace()actually usesreplaceAll()as part of its implementation. But not in the case of the OP.