java String, replaceall() 但在原始字符串中保留大小写

Noj*_*Noj 2 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 :(
            }
        }
Run Code Online (Sandbox Code Playgroud)

在这个循环之后,文本将是“狮子是一种生活在热带草原中的 mamifer ”,像预期的那样用蓝色着色,但我不期望用大写

mez*_*ker 5

你在你的问题中提供的代码执行以下操作:它检查输入的字符串不区分大小写的"LION",并"SAVANA"与各替换"<b style=\"...\">LION</b>""<b style=\"...\">SAVANA</b>"分别。

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

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