How to replace a string if it is not contained between '<' and '>'

I need to replace parts of the text, but only if its substrings are not enclosed between '<' and '>'.

For example, if I have the following text

 <text color='blue'>My jeans are red</text> <text color='red'>I am wearing a red t-shirt</text> <text color='yellow'>I like red fruits</text> 

and I want to replace the word β€œred” with another word, how can I replace a word in this text without replacing the words contained between β€œ<” and '>'? I tried to write a regex for this, but I failed ...

The dumb way that I thought is to parse all the text (char to char), see if I'm inside or outside <...> and replace the appearance of the text only if I'm outside ... I think that There must be a smarter way!

+4
source share
4 answers

if it is ok for you?

if you just want to replace on a separate line :

 final String s = "<text color='red'>I am wearing a red t-shirt</color>"; System.out.println(s.replaceAll("(?<=>)(.*?)red", "$1blue")); 

will print

 <text color='red'>I am wearing a blue t-shirt</color> 

multi-line case :

 final String s = "<text color='red'>I am wearing a red t-shirt</color>\n<text color='red'>You are wearing a red T-shirt</color>"; System.out.println(s.replaceAll("(?m)^(.*?)(?<=>)([^>]*?)red", "$1$2blue")); 

output:

 <text color='red'>I am wearing a blue t-shirt</color> <text color='red'>You are wearing a blue T-shirt</color> 
+1
source

For a little longer, using an array of supporting lines, replace only the line between the open and close < ... > tags with other text.

  String input ="<text color='red'>I am wearing a red t-shirt</color>"; String [] end = null; String [] start = input.split("<"); if (start!=null && start.length>0) for (int i=0; i<start.length;i++){ end = start[i].split(">"); } if (end!=null && end.length>0) for (int k=0; k<end.length;k++){ input.replace(end[k], end[k].replace("red", "blue")); } 
0
source

I will replace any "red" that is not followed by a ">". After that, check the pairs '<' and '>'.

 String xml = "<text color='blue'>My jeans are red</text> <text color='red'>I am wearing a red t-shirt</text>red"; xml = xml.replaceAll("red(?=([^>]*<[^>]*?>)*[^<|>]*$)", "blue"); System.out.println(xml); 

Here is the result:

 <text color='blue'>My jeans are blue</text> <text color='red'>I am wearing a blue t-shirt</text> 
0
source
 Text=Text.replace(" red ", " blue "); Text=Text.replace(" red<"," blue<"); Text=Text.replace(" red.", " blue."); 
-1
source

All Articles