java String, replaceall() but keep case in origina

2019-07-11 02:22发布

hello i make a program that can highlight strings into a webview(android) and i stuck at replacing string with colored one, with this piece of code

        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 :(
            }
        }

after this loop the text will be "the LION is a species of mamifer living into the SAVANA" ,colored in blue like expected but with uppercase as i don't expect

2条回答
来,给爷笑一个
2楼-- · 2019-07-11 02:51

The code that you provided in your question does the following: it checks the input string case-insensitively for "LION" and "SAVANA" and replaces each with "<b style=\"...\">LION</b>" and "<b style=\"...\">SAVANA</b>" respectively.

If you want to get the original word, use backreferences like here. With that backreference in use, your replaceAll call would look like this:

finalText = finalText.replaceAll("(?i)(" + ss + ")", "<b style = \"color:#2575ff\">$1</b>");
查看更多
戒情不戒烟
3楼-- · 2019-07-11 03:04

ok i've found how to doit, here

so finally, i just replaced this line :

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

by

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

$0 apparently is the word that i want to keep with the same case

查看更多
登录 后发表回答