简体   繁体   中英

in java using regular expressions replace + and - with “ + ” and “ - ”

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("\\\\-", " - ");

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 = ...

只需使用

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

最终答案=
str = str.replaceAll("\\\\+"," + ");
str = str.replaceAll("\\\\-", " - ");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM