用replaceAll方法替换字符串时,如何能做到不区分大小写的替换。
e.g
String A="xyzAbabABdem";
用A.replaceAll("ab","new")时能够把ab,Ab,AB都替换为“new”
应该只能用正则表达式才能完成
public class ReplaceTest
{
public static void main(String[] args)
{
String s1="xyzAbabABdem";
StringBuffer s2=new StringBuffer();
char temp[]=s1.toCharArray();
for(int i=0;i<s1.length(); i++)
{
if((temp[i] ==a ||temp[i] ==A ) && (temp[i+1] ==b ||temp[i+1] ==B ) )
{
s2.append("new");
i=i+1; //因为"ab"是两个字符,要加1 !
System.out.println("Hello World!");
}
else
{
s2.append(temp[i]);
}
}
System.out.println(s1);
System.out.println(s2);
System.out.println("Hello World!");
}
}
temp[i] ==a ||temp[i] ==A ) && (temp[i+1] ==b ||temp[i+1] ==B )
这部分如果用一个函数实现,应该可用性能好点! 以替换字符和temp[i] 为参数, 哈哈
先转换成大写或小写,再替换不就可以了吗?
:)
学习中.肯定是不能转换成全部大小写的.会破坏原字串的.
replaceAll函数也是用的正则表达式
可以直接替换
<%
String A="xyzAbabABdem";
A=A.replaceAll("ab|aB|Ab|AB","new");
out.println(A);
%>