码:
public static void main(String[] args) {
String mainTag = "HI";
String replaceTag = "667";
String text = "92<HI=/><z==//HIb><cHIhi> ";
System.out.println(strFormatted(mainTag, replaceTag, text));
mainTag = "aBc";
replaceTag = "923";
text = "<dont replacethis>abcabc< abcabcde >";
System.out.println(strFormatted(mainTag, replaceTag, text));
}
private static String strFormatted(String mainTag, String replaceTag, String text) {
return text.replaceAll("(?i)(?<=<)" + mainTag + "(?=.*>)", replaceTag);
}
因此,我只想在标记(
mainTag
)内将replaceTag
(变量)替换为<...>
(变量)。在上面的示例中,我想将
HI
内部所有出现的mainTag <...>
(不区分大小写)替换为667
,但是我的代码仅替换了第一次出现的内容。例子:
92<HI=/><z==//HIb><cHIhi>
预期产量:
92<667=/><z==//667b><c667667>
(mainTag =“ HI”,replaceTag =“ 667”)
<dont replacethis>abcabc<abcabcde>
预期产量:
<dont replacethis>abcabc<923923de>
(mainTag =“ aBc”,replaceTag =“ 923”);
注意:我的代码是错误的,不仅因为他只替换了1次,而且还因为它仅在“ mainTag”接在“
最佳答案
您只需要在这里提前看。想法是找到所有mainTags
,后跟一个>
,然后匹配成对的<>
,并替换为replaceTag
。以下正则表达式将起作用:
text.replaceAll("(?i)" + mainTag + "(?=[^<>]*>(?:[^<>]*<[^<>]*>)*[^<>]*)$", replaceTag);
说明:
(?i) # Ignore Case
mainTag # Match mainTag
(?= # which is followed by
[^<>]* # Some 0 or more characters which are not < or >
> # Close the bracket (this ensures, mainTag is between closing bracket
(?: # Start a group (to match pair of bracket)
[^<>]* # non-bracket characters
< # Start a bracket
[^<>]* # non-bracket characters
> # End the bracket
)* # Match the pair 0 or more times.
[^<>]* # Non-bracket characters 0 or more times.
)
[^<>]*)$
上面的正则表达式实际上假设括号始终是平衡的。对于不平衡的正则表达式,这可能会产生意外的结果。但是,正则表达式并不是真正的工具。
否则一个正则表达式很简单,因为它也可以正常工作:
"(?i)" + mainTag + "(?=[^<>]*>)"
这取决于您的用例。这不用担心平衡括号。您可以先尝试第二个,如果它适合所有情况,那么最好。