正则表达式替换所有忽略大小写 [英] regex replace all ignore case
本文介绍了正则表达式替换所有忽略大小写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何忽略以下示例中的大小写?
How do I ignore case in the below example?
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."
推荐答案
要进行不区分大小写的搜索和替换,您可以更改
To do case-insensitive search and replace, you can change
outText = inText.replaceAll(word, word.replaceAll(" ", "~"));
进入
outText = inText.replaceAll("(?i)" + word, word.replaceAll(" ", "~"));
避免破坏原始大写:
然而,在上述方法中,您将破坏被替换单词的大小写。这是一个更好的建议:
Avoid ruining the original capitalization:
In the above approach however, you're ruining the capitalization of the replaced word. Here is a better suggestion:
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
这篇关于正则表达式替换所有忽略大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文