0

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!

1
  • 1
    @Pshemo From what I heard here on SO, String#replace() actually uses replaceAll() as part of its implementation. But not in the case of the OP. Commented Mar 14, 2017 at 6:17

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.