簡體   English   中英

正則表達式在文本文檔的子部分中多次匹配捕獲組

[英]Regex to match capture group multiple times within subsection of text document

我正在傳遞一個XML文檔,作為文本文檔,雖然是正則表達式過程。

<YaddaYaddaPrecedingMarkup>includes (a) and (b) and (c) and (d) and ...

<MyElement>SECTIONBEGINS (a) Item A (b) Item B (c) Item C (d) Item D</MyElement>

<YaddaYaddaFollowingMarkup>includes (a) and (b) and (c) and (d) and ...

我希望我的正則表達式捕獲子彈標簽'(a)''(b)''(c)''(d)'。 (.. etc ...)出現在'MyElement'中,其文本以“SECTIONBEGINS”開頭。

我需要這個正則表達式來忽略(a)......(b)......(c)出現在我的XML-as-text中的任何其他實例。

如果我使用:

(\([a-z]\))

我在整個文件中匹配(a),(b),(c)。 那種表達方式太不受限制了。

如果我使用:

>SECTIONBEGINS(?:.*?)(\([a-z]\))(?:.*)<

我只在正確的部分內成功匹配,但我只匹配'(a)'(第一個匹配),而不匹配同一部分的(b),(c),(d)。

而且我已經嘗試了很多其他的變體,其中一些將選擇'(d)'而不是沒有似乎捕獲多個命中。

變式1:Lookbehind

(?<=SECTIONBEGINS[^>]*)\([a-z]\)

變體2:\\ G錨+捕獲組

(?:SECTIONBEGINS|\G)[^<(]*(\([a-z]\))

您需要查看Match.Group.Captures

Regex.Match(xml, @">SECTIONBEGINS (?<items>\([a-z]\) .+?)+<")
    .Groups["items"].Captures.Cast<Capture>()
    .Select(x => x.Value)

或者,如果您想將它們分組為鍵/值對:

var match = Regex.Match(xml, @">SECTIONBEGINS( (\((?<index>[a-z])\) (?<item>.+?)))+<");
Enumerable.Zip(
    match.Groups["index"].Captures.Cast<Capture>(),
    match.Groups["item"].Captures.Cast<Capture>(),
    Tuple.Create)
    .ToDictionary(x => x.Item1.Value, x => x.Item2.Value)

編輯:如果您不關心子彈標簽,您可以通過以下方式提取項目:

Regex.Match(xml, @">SECTIONBEGINS( (\((?<index>[a-z])\) (?<item>.+?)))+<")
    .Groups["item"].Captures.Cast<Capture>()
    .Select(x => x.Value)

或者,如果要替換內容:

Regex.Replace(xml, @">SECTIONBEGINS( (\((?<index>[a-z])\) (?<item>.+?)))+<",
    m => string.Format(">SECTIONBEGINS {0}<", string.Join(" ", m.Groups["item"]
        .Captures.Cast<Capture>()
        .Select((x,i) => string.Format("({0}) {1}",
            (char)(((int)'a')+i),
            x.Value.ToUpper() // TODO: your replace logic here
    ))))
)

暫無
暫無

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

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