gpt4 book ai didi

java - 正则表达式选择特定字符串前面的字符串

转载 作者:行者123 更新时间:2023-11-30 06:15:41 24 4
gpt4 key购买 nike

我在java对象中有大的xml。我想替换

<countryChannel countryCode="CountryCode"/>

with

<countryChannel countryCode="CountryCode" active="true"></countryChannel>

这是示例 xml(输入)

</articleMedia>
<channels>
<countryChannel countryCode="CountryCode"/>
</channels>

</articleMedia>
<channels>
<countryChannel countryCode="CountryCode"/>
</channels>

</articleMedia>
<channels>
<countryChannel countryCode="CountryCode"/>
</channels>

请问使用正则表达式如何才能仅选择countryChannelcountryCode=“CountryCode”前面的所有字符串中的“/>”部分?

我有一个正则表达式,它只选择整个字符串 https://regex101.com/r/NLHy2Y/1 ,但是如何仅选择“countryChannelcountryCode=”CountryCode“”之前的所有“/>”?

最佳答案

在这种情况下,您甚至不需要正则表达式。您可以将 String.replace() 与正确的文本一起使用:

String input = "<countryChannel countryCode=\"CountryCode\"/>\r\nsalala\r\n<countryChannel countryCode=\"CountryCode\"/>";
String replacement = input.replace("<countryChannel countryCode=\"CountryCode\"/>", "<countryChannel countryCode=\"CountryCode\" active=\"true\"></countryChannel>");
System.out.println(replacement);

这里有一个技巧:如果您想将 XML 编辑为文本,那么您必须对 xml 的序列化方式做出一些假设。在这种情况下,我做出了这样的假设:

  1. 您只想编辑那些具有一个 <countryChannel> 属性的 countryCode 标记
  2. 它们的值始终是 CountryCode
  3. 所有这些标签都像这样序列化:<countryChannel countryCode="CountryCode"/>

您可能还想包含其他国家/地区代码。只要它们不包含引号,您就可以使用以下正则表达式来完成:"<countryChannel countryCode=\"([^\"]*)\"/>" 并在替换中使用反向引用 $1。在这种情况下,您需要 String.replaceAll() 方法,因为它评估正则表达式。代码如下:

String input = "<countryChannel countryCode=\"CountryCode123\"/>\r\nsalala\r\n<countryChannel countryCode=\"CountryCode456\"/>";
String replacement = input.replaceAll("<countryChannel countryCode=\"([^\"]*)\"/>", "<countryChannel countryCode=\"$1\" active=\"true\"></countryChannel>");
System.out.println(replacement);

说明:[^...] 是一个否定字符类。 IE。除了那些角色之外的一切。因此 [^"]* 匹配除引号之外的字符。这很酷,因为我们想在实际属性的末尾停止匹配。

因此,您可以检查您的大 xml 文件并确保您有正确的假设。

免责声明:

不要将此类正则表达式投入生产。这些正则表达式非常适合您自己编辑文件,只要您手动检查它们即可。但是,对于生产,您最好使用 XSLT。

关于java - 正则表达式选择特定字符串前面的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49255527/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com