0

in java im trying to use string.replaceall to replace "+" and "-" with " + " and " - "

However str.replaceall("+"," + ") results in an error,
so I tried str.replaceall("\+"," + ") and str.replaceall("\Q+\E"," + ")

neither worked

after that i tried str.replaceall("\+"," + ") but forgot to mention it originally, but it does not affect my strings which contain "1x^5+2x^4+6x^3+3x^2+4x^0"

Final answer =
str = str.replaceAll("\\+"," + ");
str = str.replaceAll("\\-", " - ");

2
  • Contrary to popular belief, slash and backslash are not the same character. :) Commented Mar 19, 2011 at 18:02
  • was an error when posting to stackoverflow used correct slashes in the program. Commented Mar 19, 2011 at 18:05

3 Answers 3

3

No need for a regex, just use str = str.replace("+", " + ").replace("-", " - ");

Note that since strings are immutable, you need to use the returned string, hence the str = ...

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

1 Comment

turned out it was a combination. str = str.replaceAll("\\+"," + "); str = str.replaceAll("\\-", " - ");
2

Just use

str.replaceall("\\+"," + ")

Comments

-1

Final answer =
str = str.replaceAll("\\+"," + ");
str = str.replaceAll("\\-", " - ");

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.