java 如何以简单的方式仅用一个字符替换多个字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6960412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How I replace multiple chars with only one char in a simple way?
提问by Renato Dinhani
I want to replace some chars with accents in a String like this example:
我想用字符串中的重音替换一些字符,如下例所示:
str.replace('á','a');
str.replace('a','a');
str.replace('?','a');
This will work, but I want to know if there is some simple way where I pass all the chars to be replaced and the char that will replace they. Something like these:
这会起作用,但我想知道是否有一些简单的方法可以让我传递所有要替换的字符以及将替换它们的字符。像这样的东西:
replace(str,"áa?",'a');
or:
或者:
char[] chars = {'á','a','?'};
replace(str,chars,'a');
I looked at StringUtils
from Apache Lang
, but not exists this way I mentioned.
我StringUtils
从看Apache Lang
,但不存在我提到的这种方式。
采纳答案by Sam DeHaan
You're going to want to look at
你会想看
str.replaceAll(regex, replacement);
Off the top of my head, I can't recall Java's regex format, so I can't give you a format that catches those three. In my mind, it would be
在我的脑海里,我想不起来 Java 的正则表达式格式,所以我不能给你一个格式来捕捉这三个。在我看来,这将是
'[áa?]'
回答by Marc B
Try .replaceAll()
: str.replaceAll('[áa?]', 'a');
尝试.replaceAll()
: str.replaceAll('[áa?]', 'a');
回答by Matt_Bro
This should work str.replaceAll("[áa?]",'a')
这应该有效 str.replaceAll("[áa?]",'a')
回答by Julian Fondren
str.replaceChars("áa?", "aaa");
回答by Amol Katdare
Maybe a simple originalString.replaceAll("á|a|?", "a")
will do
也许一个简单的originalString.replaceAll("á|a|?", "a")
就行
回答by PhD
str.replaceAll("[áa?]","a");
Try this - it's a regex patter saying replace occurrence of each of the characters by "a"
试试这个 - 这是一个正则表达式模式,说用“a”替换每个字符的出现