gpt4 book ai didi

c# - 基于控制台格式代码的格式字符串

转载 作者:行者123 更新时间:2023-11-30 20:35:02 24 4
gpt4 key购买 nike

如何使用格式化代码格式化字符串,以便为 windows cmd 设置格式化字符串?


所以基本上我有一个类似 ~b~Hello World~r~ 的字符串.

当我将它输出到 cmd 时,它应该显示为 <blue from here on>Hello World<reset to normal> .


据我所知,cmd 有一些 Unicode 字符可以更改以下文本格式,但我不记得它们(类似于 \u00234 )


所以我想到的是:

public string FormatString(string input)
{
input = Regex.Replace(input, "~b~", "<unicode for blue>", RegexOptions.IgnoreCase);
input = Regex.Replace(input, "~r~", "<Unicode for reset>", RegexOptions.IgnoreCase);
return input;
}

最佳答案

据我所知,在 Windows 控制台应用程序(如 cmd.exe)中没有此类控制代码。有一些创造性的方法可以达到类似的效果。其中之一是 How to echo with different colors in the Windows command line .我出于好奇尝试了一下,效果很好。它使用了一些 jscript 魔法。对于日常使用,如果您需要转义码格式化功能,您可能会发现其中一种 bash shell 模拟器更有用。 ( How to develop in Linux-Like Shell (bash) on Windows? )

更新:

我拼凑了一些非常快速和肮脏的东西来演示一种使用“代码”的方法,其风格与您在问题中使用的风格相似。这可能不是“最佳”方式。但这可能会激发一个想法。

class Program
{
static void Main(string[] args)
{
@"
This is in ~r~red~~ and this is in ~b~blue~~. This is just some more text
to work it out a bit. ~g~And now a bit of green~~.
".WriteToConsole();
Console.ReadKey();
}
}

static public class StringConsoleExtensions
{
private static readonly Dictionary<string, ConsoleColor> ColorMap = new Dictionary<string, ConsoleColor>
{
{ "r", ConsoleColor.Red },
{ "b", ConsoleColor.Blue },
{ "g", ConsoleColor.Green },
{ "w", ConsoleColor.White },
};
static public void WriteToConsole(this string value)
{
var position = 0;
foreach (Match match in Regex.Matches(value, @"~(r|g|b|w)~([^~]*)~~"))
{
var leadingText = value.Substring(position, match.Index - position);
position += leadingText.Length + match.Length;
Console.Write(leadingText);
var currentColor = Console.ForegroundColor;
try
{
Console.ForegroundColor = ColorMap[match.Groups[1].Value];
Console.Write(match.Groups[2].Value);
}
finally
{
Console.ForegroundColor = currentColor;
}
}
if (position < value.Length)
{
Console.Write(value.Substring(position, value.Length - position));
}
}
}

我认为可能有一种方法可以让正则表达式捕获前导文本。但是我没有太多时间去试验。我很想看看是否有一种模式可以让正则表达式完成所有工作。

关于c# - 基于控制台格式代码的格式字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38469869/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com