我必须替换文本的一部分,但前提是它的子字符串不包含在“<”和“>”之间。
例如,如果我有以下文字
<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>
我想用另一个词替换单词“red”,如何在不替换“<”和“>”之间的单词的情况下替换该文本中的单词? 我试图为此编写一个正则表达式,但我没有成功...
我认为一个愚蠢的方法是分析所有文本(一个字符一个字符),看看我是在 <...> 的内部还是外部,如果我在外部...我就替换文本的出现认为应该有更聪明的方法!
最佳答案
这对你来说合适吗?
如果您只想在单行中进行替换:
final String s = "<text color='red'>I am wearing a red t-shirt</color>";
System.out.println(s.replaceAll("(?<=>)(.*?)red", "$1blue"));
将打印
<text color='red'>I am wearing a blue t-shirt</color>
多行大小写:
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"));
输出:
<text color='red'>I am wearing a blue t-shirt</color>
<text color='red'>You are wearing a blue T-shirt</color>
关于java - 如果不包含在 '<' 和 '>' 之间,如何替换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14729175/