我正在尝试突出显示文件中的特定单词,并在控制台中以突出显示的单词显示所有文本。
我曾尝试使用正则表达式对其进行优化,但在尝试将其显示的每个句子中的所需匹配项都涂成红色时陷入困境。因此,我改为使用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();
答案 0 :(得分:0)
这是使用正则表达式的命题:
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();
}
但是,我担心子字符串重复的性能...