簡體   English   中英

正則表達式匹配字符串中的多個子字符串

[英]Regex match multiple substrings inside a string

所以我有一個字符串,其中包含多次出現的子字符串。 所有這些字符串都具有以下格式: <c@=someText>Content<c>

例:

This combination of plain text and <c=@flavor> colored text<c> is valid. <c=@warning>Multiple tags are also valid.<c>

我想通過正則表達式提取每個子字符串。 但是,如果我使用以下正則表達式<c=@.+?(?=>)>.*<c>它匹配從第一個<c...到最后一個<c> 我想要的是將每個子字符串作為一項。 我該怎么做,如果我不能用正則表達式來做,那是實現我的目標的最佳方法。

您可以使用命名的捕獲組以及前瞻性和后瞻性來獲取“類型”和“文本”:

var pattern = @"(?<=<c=@)(?<type>[^>]+)>(?<text>.+?)(?=<c>)";
var str = @"This combination of plain text and <c=@flavor> colored text<c> is valid. <c=@warning>Multiple tags are also valid.<c>";

foreach (Match match in Regex.Matches(str, pattern))
{
   Console.WriteLine(match.Groups["type"].Value);
   Console.WriteLine(match.Groups["text"].Value);

   Console.WriteLine();
}

輸出:

flavor
 colored text

warning
Multiple tags are also valid.

圖案:

(?<=<c=@) :尋找<c=@

(?<type>[^>]+)> :抓取所有內容,直到> ,將其稱為type

(?<text>.+?) :抓取所有內容直到超前,將其稱為text

(?=<c>) :找到<c>時停止

string input = @"This combination of plain text and <c=@flavor> colored text<c> is valid. <c=@warning>Multiple tags are also valid.<c>";

var matches = Regex.Matches(input, @"<c=@(.+?)>(.+?)<c>")
                .Cast<Match>()
                .Select(m => new
                {
                    Name = m.Groups[1].Value,
                    Value = m.Groups[2].Value
                })
                .ToList();

暫無
暫無

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

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