Skip to main content
 首页 » 编程设计

c#之使用多行和组的正则表达式

2024年01月28日3098°冷暖

大家好,我有一个关于在正则表达式中使用多行的快速问题:

正则表达式:

 string content = Regex.Match(onix.Substring(startIndex,endIndex - startIndex), @">(.+)<", RegexOptions.Multiline).Groups[1].Value; 

这是我正在阅读的文本字符串:

    <Title> 
         <TitleType>01</TitleType> 
         <TitleText textcase="02">18th Century Embroidery Techniques</TitleText> 
    </Title> 

这是我得到的:

01 

我想要的是之间的一切

 <Title> and </Title>. 

当一切都在一行上时,这非常有效,但由于从另一行开始,它似乎会跳过它或不将其包含在模式中。

非常感谢任何帮助。

请您参考如下方法:

您还必须使用单行选项以及多行:

string content = Regex.Match(onix.Substring(startIndex,endIndex - startIndex), @">(.+)<", RegexOptions.Multiline | RegexOptions.Singleline).Groups[1].Value; 

但是帮自己一个忙,停止使用正则表达式解析 XML!请改用 XML 解析器!

您可以使用 XmlDocument 解析 XML 文本类,并使用 XPath selectors获取您感兴趣的元素:

XmlDocument doc = new XmlDocument(); 
doc.LoadXml(...);                              // your load the Xml text  
 
XmlNode root = doc.SelectSingleNode("Title");  // this selects the <Title>..</Title> element 
                                               // modify the selector depending on your outer XML  
Console.WriteLine(root.InnerXml);              // displays the contents of the selected node