我想要做的是從字符串解析一些自定義標記,但也獲得未標記的內容。例如,我有以下字符串正則表達式來捕獲標記和未標記的內容
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場比賽,上面這兩個,還有「你好世界」和「這是正常的」。
這是正則表達式可能嗎?
舉一個例子,這是我目前的功能:
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就是一個包含文本和顏色的容器),如果你想嘗試與修修補補XML,你可以嘗試這樣的一個解決方案
這是如何關係到WPF? – Clemens
是輸入XML還是它看起來像XML? –
@Clemens抱歉,我的錯,我習慣於標記爲WPF,因爲我的許多問題需要不同的答案,因爲我在WPF中工作。習慣的力量。 – Ben