c# - 用于捕获标记和未标记内容的正则表达式

标签 c# regex

我想要做的是从字符串中解析一些自定义标签,同时也获取未加标签的内容。例如,我有以下字符串

Hello World <Red>This is some red text </Red> This is normal <Blue>This is blue text </Blue>

我有一个可以使用的正则表达式来获取标记的内容

<(?<tag>\w*)>(?<text>.*)</\k<tag>>

但是,这会返回

 tag: Red
 text: This is some red text
 tag: Blue
 text this is blue text

我还需要为未标记的内容匹配,所以我会得到 4 个匹配项,两个像上面那样,还有“Hello World”和“This is normal”。

这是否可以通过正则表达式实现?

例如,这是我当前的功能:

 public static List<FormattedConsole> FormatColour(string input)
    {
        List<FormattedConsole> formatted = new List<FormattedConsole>();
        Regex regex = new Regex("<(?<Tag>\\w+)>(?<Text>.*?)</\\1>", RegexOptions.IgnoreCase
                | RegexOptions.CultureInvariant
                | RegexOptions.IgnorePatternWhitespace
                | RegexOptions.Compiled
        );

        MatchCollection ms = regex.Matches(input);

        foreach (Match match in ms)
        {
            GroupCollection groups = match.Groups;
            FormattedConsole format = new FormattedConsole(groups["Text"].Value, groups["Tag"].Value);
            formatted.Add(format);
        }

        return formatted;
    }

如前所述,这只会返回标签之间的匹配项。我还需要获取没有标签的文本。

(顺便说一句,FormattedConsole 只是一个包含文本和颜色的容器)

最佳答案

你可以试试这个:

string sentence = "Hello World <Red>This is some red text </Red> This is normal <Blue>This is blue text </Blue>";
string[] matchSegments = Regex.Split(sentence,@"(<\w+>)(.*?)<\/\w+>");
foreach (string value in matchSegments)
{
    if(value.Contains("<") && value.Contains(">"))
        Console.Write(value);
    else
        Console.WriteLine(value);   
}

输出:

Hello World
<Red>This is some red text
 This is normal
<Blue>This is blue text

Run the code here

关于c# - 用于捕获标记和未标记内容的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41221848/

相关文章:

c# - F# 函数与 C# "Func"的对比

c# - Linq 中的计算字段按总和分组

REGEXP_REPLACE 捕获组

javascript - |\s 的目的/作用是什么?在 ([\s\S]+|\s?)

regex - Sed 动态反向引用替换

c# - 服务器端的 Blazor : using MongoDB for Identity management

c# - 如何在同一台远程机器中有效地复制 UNC 路径

c# - 如何在 C# 中将字符串转换为 Flags 枚举格式

java - 从字符串中的金额中提取数字

regex - 使用 SED 或 AWK 从文件中删除行