2

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

mezzodrinker
  • 998
  • 10
  • 28
Noj
  • 164
  • 1
  • 15

2 Answers2

5

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>");
mezzodrinker
  • 998
  • 10
  • 28
  • @Noj Yeah, you're right. `$0` would've done the job as well. – mezzodrinker Oct 14 '15 at 20:16
  • ahaha ok, i think its better to doit with second parenthesis? right? – Noj Oct 14 '15 at 20:18
  • 1
    @Noj I added them in case you wanted to extend the regex with some other stuff. The paranthesis `()` around the variable `ss` turn it into a capturing group. Since this one is the first capturing group (`(?i)` is not a capturing group), I accessed it with `$1` afterwards. `$0` accesses the whole match, so for example if you used `"(?i)"+ss+" something"` as your regex, `something` would've been added to your replacement as well. – mezzodrinker Oct 14 '15 at 20:21
  • thank you again, i start to understand a bit more this replaceall function with filters. Now im so happy that my android encyclopedia (based on sparql queries) is better :D... – Noj Oct 14 '15 at 20:25
  • @Noj No worries, that's why I answered you. If you ever need to tinker with regular expressions again, I as a programmer myself recommend using a tool like [regex101](https://regex101.com/). – mezzodrinker Oct 14 '15 at 20:34
3

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

Community
  • 1
  • 1
Noj
  • 164
  • 1
  • 15