2015-11-02 34 views
-1

比方说,我有这样的事情:如何查找,替换并将包含xml的字符串拆分为数组?

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 

我找<foo>带或不带字符串属性,需要相应地打破字符串。

我发现了一种简单的方法,用一些值替换下面的东西。

例如:matcher.replaceAll("bar")这就造成了像:

Your number is bar and your code is bar 

我想看到什么是至关断串入一个数组或列表,每当我看到标签<foo>的字符串值。

+1

String.split是你需要的 –

+0

嵌套标签可能吗?像'abc def xyz'?如果是这样,他们应该如何处理? – Pshemo

+1

@ JunedAhsan我不这么认为。 OP需要更像解析这个半xml字符串的内容。 –

回答

0

假设您的文本的该格式没有任何嵌套标签你应该罚款的东西,如:

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

这将:

  1. trim()在开始和结束修剪空格您文字
  2. replaceAll("<foo\\s+attr=\"([^\"]+)\">", "<foo>$1|")将每个<foo attr="data">替换为<foo>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>. 
    //     ^^^^^^^ 
    

    所以现在我们只有<foo></foo>所以我们可以简单地拆分这些标记

  3. replaceAll("^<foo>|</foo>\\.?$","")现在我们的字符串为分裂做准备的<foo></foo>我们需要删除字符串开头和结尾的字符串以避免结果数组中有空元素

  4. split("\\s?</?foo>\\s?");分割为<foo></foo>(包括围绕它们的可选空白区域。