Kalendj
@Kalendj
Изучаю C#, Unity, изометрию

Как выводить на консоль ключевые слова особым цветом, отличным от всего остального текста?

Я знаю, что мне нужен Rege. Но я не могу понять, как это сделать. Получилось так, но всё равно не выходит.

string text = "This is the great city of Sevsar, the harbor of humanity";

string[] keywords = { "great", "harbor" };

string checkedText = highlightColor(text, keywords);
Console.WriteLine(checkedText);

string highlightColor(string text, string[] keywords, ConsoleColor highlightColor = ConsoleColor.Red)
{
    foreach(string keyword in keywords)
    {
        text = Regex.Replace(text, @"\b" + keyword + @"\b", delegate (Match m)
    {
        Console.ForegroundColor = highlightColor;
        string highlighted = m.Value;
        Console.ResetColor();
        return highlighted;

    }, RegexOptions.IgnoreCase);

    } 
    return text;

}
  • Вопрос задан
  • 68 просмотров
Решения вопроса 1
Mike_Ro
@Mike_Ro
Python, JS, WordPress, SEO, Bots, Adversting
Вы изменяете цвет консоли внутри делегата с уже сформированной строкой. Как вариант, можно разделить текст на слова и выводить нужные слова с нужным цветом:
using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main(string[] args)
    {
        string text = "This is the great city of Sevsar, the harbor of humanity";
        string[] keywords = { "great", "harbor" };

        HighlightKeywords(text, keywords, ConsoleColor.Red);
        Console.WriteLine();
    }

    public static void HighlightKeywords(string text, string[] keywords, ConsoleColor highlightColor)
    {
        string pattern = $@"\b({string.Join("|", keywords)})\b";
        MatchCollection matches = Regex.Matches(text, pattern, RegexOptions.IgnoreCase);

        int lastIndex = 0;
        foreach (Match match in matches)
        {
            Console.Write(text.Substring(lastIndex, match.Index - lastIndex));

            Console.ForegroundColor = highlightColor;
            Console.Write(match.Value);
            Console.ResetColor();

            lastIndex = match.Index + match.Length;
        }

        Console.Write(text.Substring(lastIndex));
    }
}

КартинкО

6641ffe274e9d095852691.png
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы