简体   繁体   English

Java 正则表达式匹配 XML 标签

[英]Java Regex to Match XML tags

I am trying a figure out a regex pattern to match XML tags.我正在尝试找出一个正则表达式模式来匹配 XML 标签。

I have two kinds of XML tags.我有两种 XML 标签。 First kind第一类

<myTag value="One" value="Two">SomeContentHere</myTag>

This tag I could match with the following regex pattern.这个标签我可以匹配下面的正则表达式模式。

<myTag[\s\S]*?>[\s\S]*?<\/myTag>

Second kind is, I have the same tag that appear as <myTag value="One" value="Two"/> .第二种是,我有与<myTag value="One" value="Two"/>相同的标签。 I struggle on finding a regex to match these kinds of XML tags.我很难找到一个正则表达式来匹配这些类型的 XML 标签。 I need to match the entire XML like in the above matching in the first kind.我需要像上面的第一种匹配一样匹配整个 XML。 My objective is to find a regex pattern that can capture both the above scenarios.我的目标是找到一个可以捕捉上述两种情况的正则表达式模式。

I tried something like <myTag[\s\S]*?>[\s\S]*?[<\/myTag>]?我尝试了类似<myTag[\s\S]*?>[\s\S]*?[<\/myTag>]? but, in this case, this pattern fails to capture my first XML tag type但是,在这种情况下,此模式无法捕获我的第一个 XML 标记类型

Kindly help me.请帮助我。

There are tons of answers here in this community on why its bad to use regex for this.这个社区中有很多关于为什么使用正则表达式不好的答案。 Having said that here is the approach for this problem.话虽如此,这是解决此问题的方法。 Convert your string to a Document if it is possible.如果可能,将您的字符串转换为文档。 It is possible if String is a valid xml.如果 String 是有效的 xml,则有可能。 Then look for the desired tag in the Document.然后在 Document 中查找所需的标签。 Code is:代码是:

private boolean containsTag(String xml, String tagName)
    {
        Document doc = getDocument(xml);
        if ( doc != null )
        {
           NodeList list = doc.getElementsByTagName(tagName);
           return list != null && list.getLength() > 0;
        }
        return false;
    }


    private static Document getDocument(String xml) 
    {

         try
         {
             DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
             Document doc = docBuilder.parse(new InputSource(new StringReader(xml)));
             return doc;
         } 
         catch (Exception e) 
         {
             e.printStackTrace();
         }
         return null;
   }

• For your first type of tag use: (<myTag)([\s\S]*?)(>)([\s\S]*?)(<\/myTag>) • 对于您的第一种类型的标签,请使用: (<myTag)([\s\S]*?)(>)([\s\S]*?)(<\/myTag>)

• For your second type of tag use: (<myTag)([\s\S]*?)(\/>) • 对于第二种类型的标签,请使用: (<myTag)([\s\S]*?)(\/>)

• For both type at the same time use: (<myTag)([\s\S]*?)(\/>)|(<myTag)([\s\S]*?)(>)([\s\S]*?)(<\/myTag>) • 对于两种类型同时使用: (<myTag)([\s\S]*?)(\/>)|(<myTag)([\s\S]*?)(>)([\s\S]*?)(<\/myTag>)

FirstTypeExample第一种类型示例

SecondTypeExample第二类示例

BothTypeAtTheSameTimeExample BothTypeAtTheSameTime 示例

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

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