我想从String中替换多个不区分大小写的字符串.
我本来可以用的:
org.apache.commons.lang.StringUtils.replaceEach(text, searchList, replacementList)
但适用于区分大小写的字符串.
是否有类似的方法适用于不区分大小写的字符串?
static String[] old = {"ABHISHEK","Name"};
static String[] nw = {"Abhi","nick name"};
static String s="My name is Abhishek";
System.out.println(StringUtils.replaceEach(s, old, nw));
Run Code Online (Sandbox Code Playgroud)
输出:
My name is Abhishek
Run Code Online (Sandbox Code Playgroud)
预期:
My nick name is Abhi
Run Code Online (Sandbox Code Playgroud)
您可以尝试使用正则表达式进行存档
例
String str = "Dang DANG dAng dang";
//replace all dang(ignore case) with Abhiskek
String result = str.replaceAll("(?i)dang", "Abhiskek");
System.out.println("After replacement:" + " " + result);
Run Code Online (Sandbox Code Playgroud)
结果:
更换后:Abhiskek Abhiskek Abhiskek Abhiskek
编辑
String[] old = {"ABHISHEK","Name"};
String[] nw = {"Abhi","nick name"};
String s="My name is Abhishek";
//make sure old and nw have same size please
for(int i =0; i < old.length; i++) {
s = s.replaceAll("(?i)"+old[i], nw[i]);
}
System.out.println(s);
Run Code Online (Sandbox Code Playgroud)
结果:
我的昵称是阿比
基本理想:正则表达式忽略大小写和replaceAll()
从评论@flown(谢谢)你需要使用
str.replaceAll("(?i)" + Pattern.quote(old[i]), nw[i]);
Run Code Online (Sandbox Code Playgroud)
因为正则表达式处理一些具有不同含义的特殊字符,例如:.asany single character
所以使用Pattern.quotewill会这样做.
| 归档时间: |
|
| 查看次数: |
138 次 |
| 最近记录: |