3

Suppose I have a string like this:

"abc%\%%%%"

I want to replace multiple %%% with only one %. I tried something like

String st = "abc%\%%%%".replaceAll("(%)\\1+", "$1");

But that would also turn "\%%" into "\%", which is not what I want. In other words, I want to replace multiple % but leave alone those preceded by a backslash.

What regex should I use? Thanks

2 Answers 2

2

Try,

String st = "abc%\\%%%%".replaceAll("([%])+","$1");
       st = "Not%%%%\\%%%%sure but%%%\\%%%%%try out".replaceAll("(\\\\)([%])+","$1$2");
Sign up to request clarification or add additional context in comments.

Comments

0

Try this

String st = "abc%\\%%%%";
String regex = "([\\\\]%)%+";
String result= st.replaceAll(regex,"\\\\%%");

result is abc%\%%

If you want to check the correctness, you can use this statement

 String result= st.replaceAll(regex,"\\\\%R");

result is abc%\%R (which confirms that % preceded by backlash is left alone.)

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.