Friday, 15 May 2015

java - How to replace a string if not contained between '' -



java - How to replace a string if not contained between '<' and '>' -

i have replace portions of text, if substrings not contained between '<' , '>'.

for example, if have next text

<text color='blue'>my jeans red</text> <text color='red'>i wearing reddish t-shirt</text> <text color='yellow'>i reddish fruits</text>

and want replace word "red" word, how can replace word in text without replacing ones contained between '<' , '>'? tried write regular look did not succeed...

a dumb way thought analyze text (char char), see if within or outside of <...> , replace occurence of text if outside... think there should smarter way!

if ok you?

if want replacement in single line:

final string s = "<text color='red'>i wearing reddish t-shirt</color>"; system.out.println(s.replaceall("(?<=>)(.*?)red", "$1blue"));

will print

<text color='red'>i wearing bluish t-shirt</color>

multi-line case:

final string s = "<text color='red'>i wearing reddish t-shirt</color>\n<text color='red'>you wearing reddish t-shirt</color>"; system.out.println(s.replaceall("(?m)^(.*?)(?<=>)([^>]*?)red", "$1$2blue"));

output:

<text color='red'>i wearing bluish t-shirt</color> <text color='red'>you wearing bluish t-shirt</color>

java android regex string

No comments:

Post a Comment