【问题标题】:How to print string format which is entered from Console.Readline() aa1234aa, in this format aa-1234-aa?如何以这种格式aa-1234-aa打印从Console.Readline()aa1234aa输入的字符串格式?
【发布时间】:2018-02-27 00:03:16
【问题描述】:

给定一个输入字符串,例如“KK1234KK”,我怎样才能让它打印出来并附加格式:“KK-1234-KK”?在代码中我希望能够做这样的事情:

string LicensePlate = "KK1234KK";

Console.WriteLine(string.Format("Custom: {0:##-####-##}", LicensePlate));

【问题讨论】:

  • 提示:String.Format 仅适用于数字和日期数据类型。要执行此类操作,您可能需要考虑使用正则表达式。
  • 您对“自定义格式”的期望输出是什么?
  • 我想在 Console.ReadLine() 中插入 kk1234kk,但我希望它以这种格式打印:kk-1234-kk。在字母和数字之间添加“-”。
  • 重新打开,因为 cmets 说String.Format 不会解决这个问题。
  • @Sym_j:我已经编辑了您的问题以添加一些文字说明。我希望你对我所做的改变感到满意。如果您不想自己回滚或进一步编辑它。

标签: c#


【解决方案1】:

您可以尝试使用正则表达式来获取此格式。这里我要找数字,两边加“-”。

        string LicensePlate = "KK1234KK";
        Regex regex = new Regex(@"\d+");
        Match match = regex.Match(LicensePlate);
        string output = Regex.Replace(LicensePlate, @"\d+","-"+match.Value+"-");

【讨论】:

    猜你喜欢
    • 2013-03-09
    • 2015-06-09
    • 1970-01-01
    • 2019-05-01
    • 1970-01-01
    • 2022-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多