java String,replaceall()但保留原始字符串中的case

时间:2015-10-14 19:28:25

标签: java regex replace

你好,我制作了一个程序,可以将字符串突出显示到webview(android)中,我坚持用彩色字符替换字符串,用这段代码

        String[] arr = "LION SAVANA".split(" ");//i split textview string to have words (here we suppose that user entered : "lion savana"


        String finalText = "the lion is a species of mamifer living into the savana"

        for (String ss : arr) {
            if (ss.length() > 2) {
                 ss = ss.replace("*","");
                finalText = finalText.replaceAll("(?i)" + ss, "<b style = \"color:#2575ff\";>" + ss + "</b>");//finally here i replace all lion or savana occurrences by blue ones -> but i not keeps case :(
            }
        }

在此循环之后,文本将是&#34; 狮子会是一种生活在 SAVANA &#34; ,像预期的那样用蓝色着色,但我不希望用大写字母

2 个答案:

答案 0 :(得分:4)

您在问题中提供的代码执行以下操作:它会对"LION""SAVANA"不区分大小写的输入字符串进行检查,并将每个字符串替换为"<b style=\"...\">LION</b>""<b style=\"...\">SAVANA</b>"分别

如果您想获取原始字词,请使用here之类的反向引用。使用该反向引用后,您的replaceAll调用将如下所示:

finalText = finalText.replaceAll("(?i)(" + ss + ")", "<b style = \"color:#2575ff\">$1</b>");

答案 1 :(得分:2)

好的,我已经找到了如何做,here

所以最后,我刚刚更换了这一行:

finalText = finalText.replaceAll("(?i)" + ss, "<b style = \"color:#2575ff\";>" + ss + "</b>");

通过

finalText = finalText.replaceAll("(?i)" + ss, "<b style = \"color:#2575ff\";>" +"$0" + "</b>");

$ 0 显然是我要保留相同案例的词