我想要做的是从字符串中解析一些自定义标签,同时也获取未加标签的内容。例如,我有以下字符串
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
关于c# - 用于捕获标记和未标记内容的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41221848/