【问题标题】: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();
}