0

I have the following code

String rplaceString="John = Max and Jing => Sira then nothing";
String replaced=rplaceString.replace("=", "==").replace("=>", "=>");
System.out.println("REPLACE STRINF==>>>>>>>>"+replaced);

Expected Output String Like this:

String expectedString="John == Max and Jing => Sira then nothing";

If I do above method, Output Looks Like:

REPLACE STRINF==>>>>>>>>John == Max and Jing ==> Sira then nothing

So, How can replace above string in expected string.

Edit: Change String Like this: John =Max and Jing => Sira then nothing

or

John= Max and Jing =>Sira then nothing

or

John=Max and Jing => Sira then nothing

4
  • 1
    what is expected output? Commented May 30, 2014 at 4:27
  • yo don't see, expected output: John == Max and Jing => Sira then nothing Commented May 30, 2014 at 4:29
  • @javanewuser Remove all the unrelated junk (that is not part of the expected/actual result) and align the output on top of each-other, and draw focus to the particular issue. In doing so you'll probably find out what the problem is. Commented May 30, 2014 at 4:30
  • You could use replaceFirst() the docs for String methods are here: docs.oracle.com/javase/6/docs/api/java/lang/String.html Commented May 30, 2014 at 4:30

3 Answers 3

7

A simple way to fix the issue would be to just add spaces around the = in your replace:

String replaced=rplaceString.replace(" = ", " == ")

Then you would only be matching the standalone = instead of the arrow as well.

EDIT:

More comprehensive answer:

String s = "John=Max and Jing=>Sira then nothing";

String t = s.replaceAll("(?<=.)=(?!>)"," == ");
t = t.replaceAll("=>", " => ").replaceAll("\\s+", " ");
System.out.println(t);
Sign up to request clarification or add additional context in comments.

6 Comments

awesome! great to hear. If you could just accept this answer I would greatly appreciate it.
wait bryan, stackoverflow takes some times for accept answers.
My bad. shouldn't get so antsy :D
Bryan, if some change string like this: John =Max and Jing => Sira then nothing ,How to do?
So let me get this straight, John =Max and Jing=> Sira then nothing is the string you want to convert into the expected output John == Max and Jing => Sira then nothing
|
0
String rplaceString = "John = Max and Jing => Sira then nothing";
    System.out.println(rplaceString.replaceAll(" = ", " == ").replaceAll("=>", "=>"));

Comments

0

If a space is always guaranteed after the = sign then you can use

String replaced=rplaceString.replace("= ", "== ").replace("=>", "=>");

Please note that I am appending a space after the '=' sign as '= ' while replacing.

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.