簡體   English   中英

Java字符串,replaceall()但在原始字符串中保留大小寫

[英]java String, replaceall() but keep case in original string

你好,我制作了一個程序,可以將字符串突出顯示到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 :(
            }
        }

在此循環之后,文本將為“ 獅子是生活在薩瓦納 (Savana)中的哺乳動物 ”,像預期的那樣以藍色顯示,但是我沒想到是大寫

您在問題中提供的代碼執行以下操作:它不區分大小寫地檢查輸入字符串中的"LION""SAVANA"並用"<b style=\\"...\\">LION</b>"替換它們"<b style=\\"...\\">LION</b>""<b style=\\"...\\">SAVANA</b>"

如果您想獲取原始單詞,請使用反向引用(如here) 使用該反向引用后,您的replaceAll調用將如下所示:

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

好,我已經找到方法了, 在這里

所以最后,我只是替換了這一行:

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

通過

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

$ 0顯然是我想保留的大小寫相同的單詞

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM