簡體   English   中英

獲取某些字符串之間的字符串數組或字符串列表(搜索多個字符串)

[英]Get an Array or List of Strings between some Strings (Search multiple Strings)

我有一個包含一些XML的字符串。 該XML包含如下輸入:

<xyz1>...</xyz1>
<hello>text between strings #1</hello>
<xyz2>...</xyz2>
<hello>text between strings #2</hello>
<xyz3>...</xyz3>

我想<hello>text between strings</hello>獲取所有這些<hello>text between strings</hello>

所以最后我想要一個包含所有<hello>...</hello>的列表或任何集合

我用Regex和Matcher嘗試過,但問題是它不適用於大字符串....如果我嘗試使用較小的字符串,則可以。 我讀了一篇關於此的博客文章,上面寫着Java Regex打破了大字符串的交替。

有什么簡單而又好的方法嗎?

編輯:

嘗試是...

String pattern1 = "<hello>";
String pattern2 = "</hello>";
List<String> helloList = new ArrayList<String>();

String regexString = Pattern.quote(pattern1) + "(.*?)" + Pattern.quote(pattern2);


Pattern pattern = Pattern.compile(regexString);

Matcher matcher = pattern.matcher(scannerString);
while (matcher.find()) {
  String textInBetween = matcher.group(1); // Since (.*?) is capturing group 1
  // You can insert match into a List/Collection here
  helloList.add(textInBetween);
  logger.info("-------------->>>> " + textInBetween);
}

您必須使用xml解析器解析xml。 比使用正則表達式容易。

DOM解析器最簡單使用,但是如果您的xml非常大,請使用SAX解析器

我強烈建議使用可用的多個公共XML解析器之一:

實現您要實現的目標非常容易(即使您將來希望詳細說明您的要求)。 如果您沒有速度和內存問題,請繼續使用dom4j 如果您希望我為您提供有關此答案的良好示例,則有大量在線資源,因為我現在的答案只是重定向您的替代選項,但我不確定您的限制是什么。


關於解析XML時的REGEX, Dour High Arch做出了很好的回應:

XML不是常規語言。 您不能使用正則表達式對其進行解析。 當您獲得嵌套標簽時,您認為可以使用的表達式將被破壞,然后當您對其進行修復時,該表達式將在XML注釋,CDATA節,處理器指令,名稱空間等條件下失效。使用XML解析器將無法工作。

用Java中的REGEX解析XML

如果必須解析XML文件,建議您使用XPath語言。 因此,您必須基本上執行以下操作:

  1. 解析DOM對象中的XML String
  2. 創建一個XPath查詢
  3. 查詢DOM

嘗試看看此鏈接

您要做的一個例子是:

String xml = ...;
try {
   // Build structures to parse the String
   DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
   // Parse the XML string into a DOM object
   Document document= builder.parse(new ByteArrayInputStream(xml.getBytes()));
   // Create an XPath query
   XPath xPath =  XPathFactory.newInstance().newXPath();
   // Query the DOM object with the query '//hello'
   NodeList nodeList = (NodeList) xPath.compile("//hello").evaluate(document, XPathConstants.NODESET);
} catch (Exception e) {
   e.printStackTrace();
}

使用Java 8,您可以使用Dynamics庫以一種簡單的方式完成此任務

XmlDynamic xml = new XmlDynamic(
    "<bunch_of_data>" +
        "<xyz1>...</xyz1>" +
        "<hello>text between strings #1</hello>" +
        "<xyz2>...</xyz2>" +
        "<hello>text between strings #2</hello>" +
        "<xyz3>...</xyz3>" +
    "</bunch_of_data>");

List<String> hellos = xml.get("bunch_of_data").children()
    .filter(XmlDynamic.hasElementName("hello"))
    .map(hello -> hello.asString())
    .collect(Collectors.toList()); // ["text between strings #1", "text between strings #2"]

參見https://github.com/alexheretic/dynamics#xml-dynamics

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM