如何忽略以下示例中的案例?
outText = inText.replaceAll(word, word.replaceAll(" ", "~"));
示例:
输入:
inText = "Retail banking Wikipedia, the free encyclopedia Retail banking "
+ "From Wikipedia. retail banking industry."
word = "retail banking"
输出
outText = "Retail~banking Wikipedia, the free encyclopedia Retail~banking " +
"From Wikipedia. retail~banking industry."
答案 0 :(得分:23)
要进行不区分大小写的搜索和替换,您可以更改
outText = inText.replaceAll(word, word.replaceAll(" ", "~"));
到
outText = inText.replaceAll("(?i)" + word, word.replaceAll(" ", "~"));
然而,在上述方法中,你破坏了替换词的大写。这是一个更好的建议:
String inText="Sony Ericsson is a leading company in mobile. " +
"The company sony ericsson was found in oct 2001";
String word = "sony ericsson";
Pattern p = Pattern.compile(word, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(inText);
StringBuffer sb = new StringBuffer();
while (m.find()) {
String replacement = m.group().replace(' ', '~');
m.appendReplacement(sb, Matcher.quoteReplacement(replacement));
}
m.appendTail(sb);
String outText = sb.toString();
System.out.println(outText);
<强>输出:强>
Sony~Ericsson is a leading company in mobile.
The company sony~ericsson was found in oct 2001
答案 1 :(得分:1)
您可以在进行搜索之前将其全部转换为小写,或者查看正则表达式修饰符Pattern.CASE_INSENSITIVE
答案 2 :(得分:1)
这是我的方式:
private String replaceAllIgnoreCase(final String text, final String search, final String replacement){
if(search.equals(replacement)) return text;
final StringBuffer buffer = new StringBuffer(text);
final String lowerSearch = search.toLowerCase(Locale.CANADA);
int i = 0;
int prev = 0;
while((i = buffer.toString().toLowerCase(Locale.CANADA).indexOf(lowerSearch, prev)) > -1){
buffer.replace(i, i+search.length(), replacement);
prev = i+replacement.length();
}
return buffer.toString();
}
似乎在我的范围内完美地工作。按我的方式做的好处是我的解决方案中没有正则表达式,这意味着如果你想要替换括号或加号(或任何其他元字符),它实际上将替换文本实际上它的内容是,而不是正则表达式中的含义。希望这有所帮助。
答案 3 :(得分:0)
您没有指定语言。
Java有Pattern.CASE_INSENSITIVE
C#和VB有RegexOptions.IgnoreCase