【问题标题】:In SpectreConsole, how to strip the tags to get a plain text string?SpectreConsole中,如何剥离标签得到纯文本字符串?
【发布时间】:2022-12-11 14:58:31
【问题描述】:

我正在使用 Spectre.Console 并且有很多这样的 AnsiConsole.MarkupLine 命令:

AnsiConsole.MarkupLine($"[lime]File size:[/] [bold]\t{file.Length,-10}[/]");

我想在文本文件中以没有颜色的纯文本输出相同的文本,比如

var msg = $"[lime]File size:[/] [bold]\t{file.Length,-10}[/]"
AnsiConsole.MarkupLine(msg);
var msgclean = AnsiConsole.StripTag(msg);
LogToFile(msgclean);

有没有办法去除标签?或者以某种方式将控制台输出重定向到文件?

【问题讨论】:

    标签: c# .net console-application spectre.console


    【解决方案1】:

    查看以下语言扩展是否适合您。正则表达式模式取自this post。通过dotnetfiddle 尝试。

    public static class StringExtensions
    {
        private static readonly Regex Whitespace = new(@"s+");
    
        public static string Flatten(this string value)
            => value is null or "" ?
                value :
                Whitespace.Replace(value.Trim(), " ");
    
        public static string StripCodes(this string sender)
            => Regex.Replace(sender, @"[[^]]*]", "")
                .Flatten();
    }
    

    【讨论】:

      【解决方案2】:

      我研究了他们的 API,发现这个扩展方法应该可以解决问题:RemoveMarkup()https://spectreconsole.net/api/spectre.console/stringextensions/29bfb33e

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-14
        • 1970-01-01
        • 2021-08-12
        相关资源
        最近更新 更多