关于替换忽略大小写的问题

wangxiaomax 2004-10-15 09:59:24
如以下代码替换掉所有的j2ee
String str="J2EE学习笔记J2ee and j2ee";
String search="j2ee";
String repl = "<font color=\"red\">"+search+"</font>";
str=str.replaceAll(search,repl);
怎么样才能忽略大小写,替换三个,而不是一个,多谢。
...全文
341 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
禽兽v5 2004-10-15
  • 打赏
  • 举报
回复
不客气
wangxiaomax 2004-10-15
  • 打赏
  • 举报
回复
太感谢cm4ever(小P) 了。结帖。
禽兽v5 2004-10-15
  • 打赏
  • 举报
回复
import java.util.regex.*;

String str="J2EE学习笔记J2ee and j2ee";
String search="j2ee";

Pattern p = Pattern.compile(search, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(str);

StringBuffer sb = new StringBuffer();
while (m.find())
{
m.appendReplacement(sb, "<font color=\"red\">"+str.substring(m.start(), m.end())+"</font>");
}

m.appendTail(sb);
System.out.println(sb.toString());
wangxiaomax 2004-10-15
  • 打赏
  • 举报
回复
可能是我表达的有问题,写的也有问题吧,我的愿意就是把原字符加亮,忽略大小写。
我刚才GOOGLE一下,java查出来有Java,也有java。
我要的就是这个效果,多谢各位帮忙。
flyforlove 2004-10-15
  • 打赏
  • 举报
回复
String search = "j2ee";
String repl = "<font color='red'>" + search + "</font>";

因为你使用了这两个式子,这就决定了,你替换后,所有的j2ee都变成小写的了,
这和一楼说的有什么区别。
由月 2004-10-15
  • 打赏
  • 举报
回复
没有现成的方法,只好用正则表达式喽。
str = str.replaceAll("(J|j)2(E|e)(E|e)",repl);
darknova 2004-10-15
  • 打赏
  • 举报
回复
不想变的话,重新复制一个不就可以了。。。
禽兽v5 2004-10-15
  • 打赏
  • 举报
回复
import java.util.regex.*;

String str = "J2EE学习笔记J2ee and j2ee";
String search = "j2ee";
String repl = "<font color='red'>" + search + "</font>";

Pattern p = Pattern.compile(search, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(str);

String str = m.replaceAll(repl);
wangxiaomax 2004-10-15
  • 打赏
  • 举报
回复
楼上的,给个例子吧。多谢了。
禽兽v5 2004-10-15
  • 打赏
  • 举报
回复
试试Pattern类的compile方法

compile
public static Pattern compile(String regex,
int flags)Compiles the given regular expression into a pattern with the given flags.


Parameters:
regex - The expression to be compiled
flags - Match flags, a bit mask that may include CASE_INSENSITIVE, MULTILINE, DOTALL, UNICODE_CASE, and CANON_EQ
Throws:
IllegalArgumentException - If bit values other than those corresponding to the defined match flags are set in flags
PatternSyntaxException - If the expression's syntax is invalid
wangxiaomax 2004-10-15
  • 打赏
  • 举报
回复
str的原始内容不可以变的
darknova 2004-10-15
  • 打赏
  • 举报
回复
先把变量str做toLowerCase,在替换就可以了

81,092

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧