簡體   English   中英

正則表達式使用多行和組

[英]Regex using Multiline and Groups

大家好,我有一個關於在正則表達式中使用多行的快速問題:

正則表達式:

 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選擇器轉到您感興趣的元素:

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

RegexOptions.Multiline只會將^$的含義更改為行的開頭/結尾,而不是整個字符串的開頭/結尾。

您想改用RegexOptions.Singleline ,結果為. 匹配換行符(以及其他所有內容)。

您可能想解析可能是XML的東西。 如果可能的話,這是首選的工作方式,而不是通過使用正則表達式進行解析。 如果不適用,請忽略。

暫無
暫無

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

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