Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 正则表达式匹配字符串中的多个子字符串_C#_Regex_String - Fatal编程技术网

C# 正则表达式匹配字符串中的多个子字符串

C# 正则表达式匹配字符串中的多个子字符串,c#,regex,string,C#,Regex,String,我有一个字符串,它包含一个子字符串的多次出现。所有这些字符串的格式如下:Content 例如: This combination of plain text and <c=@flavor> colored text<c> is valid. <c=@warning>Multiple tags are also valid.<c> 纯文本和彩色文本的组合是有效的。多个标记也有效。 我想通过正则表达式提取每个子字符串。但是,如果我使用下面的rege

我有一个字符串,它包含一个子字符串的多次出现。所有这些字符串的格式如下:
Content

例如:

This combination of plain text and <c=@flavor> colored text<c> is valid. <c=@warning>Multiple tags are also valid.<c>
纯文本和彩色文本的组合是有效的。多个标记也有效。

我想通过正则表达式提取每个子字符串。但是,如果我使用下面的regex
)>.
它匹配从第一个
开始的所有内容,您可以使用命名的捕获组以及lookaheads和lookbehinds来获取“type”和“text”:

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();
}
模式:

(?
,称之为
type

(?。+?):
抓取所有内容,直到出现前瞻,称之为
text

(?=):
找到

字符串输入时停止=@“纯文本和彩色文本的组合有效。多个标记也有效。”;
var matches=Regex.matches(输入@“(.+?)”)
.Cast()
.选择(m=>new
{
Name=m.Groups[1]。值,
Value=m.Groups[2]。Value
})
.ToList();

删除
(?=>)
,并尝试了解您的模式是如何工作的,您会找到解决方案。这可能会有所帮助:您只是想要这些标记中的文本吗?@Jonesy不,我想要标记中的文本,以及标记本身。这正是我要找的。虽然@Jonesy也有很好的代码,但您的代码更清晰,并且没有字符串来选择组s
flavor
 colored text

warning
Multiple tags are also valid.
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();