代码之家  ›  专栏  ›  技术社区  ›  Ben McCormack

我可以使用什么正则表达式从未格式化的文本体中提取XML文本体?

  •  0
  • Ben McCormack  · 技术社区  · 14 年前

    假设我有以下正文:

    Call me Ishmael. Some years ago- never mind how long precisely- having little 
    or no money in my purse, and nothing particular to interest me on shore, I 
    thought I would sail about a little and see the watery part of the world. It is  
    <?xml version="1.0" encoding="utf-8"?>
    <RootElement xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xmlns:xsd="http://www.w3.org/2001/XMLSchema">
       <ChildElement />
       <ChildElement />
    </RootElement>
    a way I have of driving off the spleen and regulating the circulation. Whenever  
    I find myself growing grim about the mouth; whenever it is a damp, drizzly 
    November in my soul; 
    

    我可以使用什么正则表达式来返回嵌入在字符串中的XML?

    注:我可以假设 <RootElement> </RootElement> 总是有相同的名字。

    2 回复  |  直到 14 年前
        1
  •  2
  •   SLaks    14 年前

    如果你知道根元素总是 <RootElement ...> <RootElement> tag,你可以这样做:

    \<\?xml .+?\</RootElement\>
    

    这个正则表达式将惰性地匹配 <?xml </RootElement> .

        2
  •  1
  •   Tim Pietzcker    14 年前

    我知道根元素并不总是被调用 RootElement

    <\?xml[^>]+>\s*<\s*(\w+).*?<\s*/\s*\1>
    

    使用 RegexOptions.SingleLine

    在C#:

    resultString = Regex.Match(subjectString, @"<\?xml[^>]+>\s*<\s*(\w+).*?<\s*/\s*\1>", RegexOptions.Singleline).Value;