繁体   English   中英

当前缀定界符和后缀定界符不同时,分割字符串的最佳方法是什么?

[英]What is the best way to split a string, when the prefix delimiters and the suffix delimiters are different?

在Java中,当每个块开头的分隔符与每个块末尾的分隔符不同时,将字符串拆分为块数组的最佳方法是什么?

例如,假设我有String string = "abc 1234 xyz abc 5678 xyz"

我想应用某种复杂的split以获得{"1234","5678"}

首先想到的是:

String[] parts = string.split("abc");
for (String part : parts)
{
    String[] blocks = part.split("xyz");
    String data = blocks[0];
    // Do some stuff with the 'data' string
}

有没有更简单/更清洁/更有效的方法?

我的目的(您可能已经猜到了)是解析XML文档。

我想将给定的XML字符串拆分为给定标签的Inner-XML块。

例如:

String xml = "<tag>ABC</tag>White Spaces Only<tag>XYZ</tag>";
String[] blocks = Split(xml,"<tag>","</tag>"); // should be {"ABC","XYZ"}

您将如何实现String[] Split(String str,String prefix,String suffix)

谢谢

您可以为这种类型的字符串编写正则表达式...

如何像\\s*((^abc)|(xyz\\s*abc)|(\\s*xyz$))\\s*它说abc开头,或xyz在年底,或abc xyz在中间(取一些空格)? 这在开始时会产生一个空值,但除此之外,似乎它会做您想要的。

import java.util.Arrays;

public class RegexDelimitersExample {
    public static void main(String[] args) {
        final String string = "abc 1234 xyz abc 5678 xyz";
        final String pattern = "\\s*((^abc)|(xyz\\s*abc)|(\\s*xyz$))\\s*";
        final String[] parts_ = string.split( pattern );
        // parts_[0] is "", because there's nothing before ^abc,
        // so a copy of the rest of the array is what we want.
        final String[] parts = Arrays.copyOfRange( parts_, 1, parts_.length );
        System.out.println( Arrays.deepToString( parts ));
    }
}
[1234, 5678]

根据您要如何处理空间,可以根据需要进行调整。 例如,

\s*((^abc)|(xyz\s*abc)|(\s*xyz$))\s*     # original
(^abc\s*)|(\s*xyz\s*abc\s*)|(\s*xyz$)    # no spaces on outside
...                                      # ...

…但是您不应该将其用于XML。

但是,正如我在评论中指出的那样,这将用于拆分具有此类定界符的非嵌套字符串。 将无法使用正则表达式处理嵌套的案例(例如abc abc 12345 xyz xyz ),因此您将无法处理常规XML(这似乎是您的意图)。 如果您实际上需要解析XML,请使用专为XML设计的工具(例如,解析器,XPath查询等)。

不要在这里使用正则表达式。 但是您也不必进行全面的XML解析。 使用XPath 在您的示例中要搜索的表达式是

//tag/text()

所需的代码是:

import org.w3c.dom.NodeList;
import org.xml.sax.*;
import javax.xml.xpath.*;

public class Test {

    public static void main(String[] args) throws Exception {

        InputSource ins = new InputSource("c:/users/ndh/hellos.xml");
        XPath xpath = XPathFactory.newInstance().newXPath();
        NodeList list = (NodeList)xpath.evaluate("//bar/text()", ins, XPathConstants.NODESET);
        for (int i = 0; i < list.getLength(); i++) {
            System.out.println(list.item(i).getNodeValue());
        }

    }
}

我的示例xml文件在哪里

<?xml version="1.0"?>
<foo>
    <bar>hello</bar>
    <bar>ohayoo</bar>
    <bar>hola</bar>
</foo>

这是最声明方式。

最好是使用专用的XML解析器之一。 请参阅有关最佳Java XML解析器的讨论

我发现此DOM XML解析器示例是一个简单而出色的示例

恕我直言,最好的解决方案是解析XML文件,这不是一件容易的事。

这里

在这里,您有另一个关于SO的问题的示例代码来解析文档,然后使用XPATH进行移动:

String xml = "<resp><status>good</status><msg>hi</msg></resp>";

InputSource source = new InputSource(new StringReader(xml));

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(source);

XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();

String msg = xpath.evaluate("/resp/msg", document);
String status = xpath.evaluate("/resp/status", document);

System.out.println("msg=" + msg + ";" + "status=" + status);

这篇文章的完整主题在这里

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM