How to solve replaceAll replaceAll

I have a little problem. I have some text that I have to read in the browser several times. Every time I open this text, automatically run the replaceAll that I wrote. It's very simple, simple, but the problem is that when I replace next time (every time I read this text) I have replaceAll replaceAll. For example, I have text:

XIII

      

I want to replace it

<b>XIII</b>

      

from:

txt.replaceAll("XIII","<b>XIII</b>")

      

The first time everything is fine, but then when I read the text again, it becomes:

<b><b>XIII</b></b>

      

This is a silly problem, but I'm starting with Java now. I read that it is possible to use regex. Can anyone post a small example?

Thank you and sorry for my bad english.

+3


source to share


3 answers


To prevent a match with an already marked line, you need a negative lookbehind:

txt.replaceAll("(?<!>)XIII","<b>XIII</b");

      

This expression looks a little confusing, but here's how it breaks down:



  • (?<! ... )

    is a pattern for negative lookbehind;
  • >

    is a specific character we want to make sure it doesn't appear before your string.

I also have to warn you that regex HTML fix usually turns into a diabolic regex update loop to handle another special case, only to see that it doesn't work on the next one. It ends with a monster that no one can read, let alone improve.

+3


source


There's a really quick fix there. Do the opposite Replace before making your own.

Let me show:



txt.replaceAll("<b>XIII</b>","XIII").replaceAll("XIII","<b>XIII</b>")

      

So you first turn yours back <b>

to normal and then bring it back with help <b>

and it will achieve the same result without adding a new level <b>

.

+1


source


How about this:

txt = txt.replaceAll ("XIII", "<b>XIII</b>").
    replceAll ("<b><b>", "<b>").replaceAll ("</b></b>", "</b>");

      

I think <b><b>

and </b></b>

do not have much meaning in HTML, so you can even remove duplicate elsewhere.

-1


source







All Articles