【问题标题】:How to find, replace and break String containing xml into array?如何查找、替换和将包含 xml 的字符串分解为数组?
【发布时间】:2015-11-02 22:33:59
【问题描述】:

假设我有类似的东西:

Sample 1: Your number is <foo>12345</foo> and your code is <foo>29939</foo>. 
Sample 2: Your number is <foo attr="x">12345</foo> and your code is <foo>29939</foo>. 

我想把这个字符串分解成一个字符串数组。

示例 1 如下所示:

array[0] = Your number is
array[1] = 12345
array[2] = and your code is
array[3] = 29939

示例 2:

array[0] = Your number is
array[1] = x|12345 (adding attr value to it)
array[2] = and your code is
array[3] = 29939

我正在寻找 &lt;foo&gt; 在字符串中有或没有属性,需要相应地打破字符串。

我找到了一种简单的方法来用一些值替换下面的东西。

示例:matcher.replaceAll("bar") 导致类似:

Your number is bar and your code is bar

每当我在字符串值中看到标记&lt;foo&gt; 时,我希望看到将字符串分解为数组或列表。

【问题讨论】:

  • String.split 是你所需要的
  • 可以嵌套标签吗?喜欢abc &lt;foo&gt;def&lt;bar&gt;123&lt;/bar&gt;xyz&lt;/foo&gt;?如果是,应该如何处理?
  • @JunedAhsan 我不这么认为。 OP 需要更像解析这半个 xml 字符串的内容。
  • 最好使用 xml 解析器。如果您不需要在标签中获取属性值形式,那么您可以轻松完成 string.split("|")
  • 没有经过测试的标签...我只是在寻找 可能有一个属性的东西,我们称之为“attr”,而且 不区分大小写,因为我在常规字符串中间获取 XML...我找到了使其不区分大小写等的方法,

标签: java arrays regex string split


【解决方案1】:

假设您的文本格式没有任何嵌套标签,您应该可以使用以下内容:

String[] arr = sentence
        .trim()
        .replaceAll("<foo\\s+attr=\"([^\"]+)\">", "<foo>$1|")
        .replaceAll("^<foo>|</foo>\\.?$","")
        .split("\\s?</?foo>\\s?");

这将:

  1. trim() 修剪文本开头和结尾的空格
  2. replaceAll("&lt;foo\\s+attr=\"([^\"]+)\"&gt;", "&lt;foo&gt;$1|") 将每个&lt;foo attr="data"&gt; 替换为&lt;foo&gt;data|,这意味着它会改变

    Your number is <foo attr=\"x\">12345</foo> and your code is <foo>29939</foo>.
    

    进入

    Your number is <foo>x|12345</foo> and your code is <foo>29939</foo>.
    //                  ^^^^^^^ 
    

    所以现在我们只有&lt;foo&gt;&lt;/foo&gt;,所以我们可以简单地将字符串拆分到这些标签上

  3. replaceAll("^&lt;foo&gt;|&lt;/foo&gt;\\.?$","") 现在准备在&lt;foo&gt;&lt;/foo&gt; 上进行拆分,我们需要删除字符串开头和结尾的部分以避免结果数组中出现空元素

  4. split("\\s?&lt;/?foo&gt;\\s?"); 拆分为 &lt;foo&gt;&lt;/foo&gt;(包括它们周围的可选空格。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-30
    • 2022-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-08
    相关资源
    最近更新 更多