我试图突出显示文件中的特定单词,并使用突出显示的单词显示控制台中的所有文本。
我试图使用正则表达式对其进行优化,但在尝试将红色显示为所显示的每个句子中的所需匹配时会卡住。所以我结束了使用For Loop替代方案。
有一个更好的方法吗?
StreamReader sr = new StreamReader("TestFile.txt");
string text = sr.ReadToEnd();
var word = text.Split(" ");
for (int i = 0; i < word.Length; i++)
{
if (word[i].Contains("World", StringComparison.CurrentCultureIgnoreCase))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Write(word[i] + " ");
Console.ResetColor();
}
else
{
Console.Write(word[i] + " ");
}
}
Console.ReadLine();
这是一个使用正则表达式的命题:
static void Main(string[] args)
{
StreamReader sr = new StreamReader("TestFile.txt");
String searched = "World";
Regex reg = new Regex(@"\b\w*" + searched + @"\w*\b");
string text = sr.ReadToEnd();
int lastIndex = 0;
MatchCollection matches = reg.Matches(text);
foreach(Match m in matches)
{
Console.Write(text.Substring(lastIndex, m.Index - lastIndex));
Console.ForegroundColor = ConsoleColor.Red;
Console.Write(m.Value);
Console.ResetColor();
lastIndex = m.Index + m.Length;
}
if(lastIndex < text.Length)
Console.Write(text.Substring(lastIndex, text.Length - lastIndex));
Console.ReadLine();
}
但是,我担心有关子串重复的表现......