【发布时间】:2016-12-20 19:51:56
【问题描述】:
我想要做的是从字符串中解析一些自定义标签,同时也获取未标记的内容。例如,我有以下字符串
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 只是一个包含文本和颜色的容器)
【问题讨论】:
-
这与 WPF 有什么关系?
-
输入的是 XML 还是只是看起来像 XML?
-
@Clemens 对不起,我的错,我习惯于标记为 WPF,因为我的很多问题需要不同的答案,因为我在 WPF 中工作。习惯的力量。
-
@AlexK.它看起来像 xml,它实际上只是一个从 lua 脚本发送到 c# 函数的字符串。允许我为一些输出着色