英文:
Replace all the characters of "+" with empty character in string java
问题
我有一个字符串
String myString = "Hello+World+How are you";
如何将myString
中所有的+
替换为空字符
我尝试过: myString.replaceAll("\\+", " ");
我想找到的是: 用于匹配+
的正则表达式,以便替换所有出现的地方
我想要实现的输出: Hello World How are you
英文:
I have a string
String myString = "Hello+World+How are you";
How to replace all "+"
in myString
with empty character
I tried with: myString.replaceAll("+"," ");
What I am trying to find: Regular expression for +
so I can replace all occurrences
Output I am trying to achieve: Hello World How are you
答案1
得分: 2
尝试像这样使用:
myString.replace("+", " ");
英文:
try with like this
myString.replace("+"," ");
答案2
得分: 1
我通常使用 Pattern.quote(String)
String myString = "Hello+World+How are you";
String replaced = myString.replaceAll(Pattern.quote("+"), " ");
我认为如果以后需要修改正则表达式,使用这种方式会减少出错的可能性。
英文:
I usually use Pattern.quote(String)
String myString = "Hello+World+How are you";
String replaced = myString.replaceAll(Pattern.quote("+"), " ");
I think it is less error-prone if you (or someone else) need to modify the regexp later.
答案3
得分: 0
你应该在Java中的任何特殊字符前面使用 \\
,这样你的代码将像这样用空格替换 +
:
myString.replaceAll("\\+", " ");
解释:\
用于转义特殊字符,而 \
本身也是一个特殊字符,这就是为什么我们必须使用 \\\\
。
英文:
You should use \\
with any special charachter in java,so your code will be like this to replace +
with whitespace:
myString.replaceAll("\\+"," ");
Explanation: \
this is used to escape special characters,and this \
itself is a special character,that is why we have to use '\'.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论