【问题标题】:Add space per 4 characters with RegEx [duplicate]使用正则表达式每 4 个字符添加空格 [重复]
【发布时间】:2014-01-13 13:08:49
【问题描述】:

每 4 个字符放置空格的正则表达式是什么

例如,我有一个这样的 IBAN 号码

BE45898287271283

我想这样格式化

BE45 8982 8727 1283

感谢任何帮助。

【问题讨论】:

  • 您真的需要正则表达式吗?我确定我可以让它与字符串比较函数一起使用
  • 制作一个匹配 4 个字符的正则 ex,并在此基础上用 4 个字符和一个空格替换
  • @D.Rattansingh 我以前从未使用过字符串比较函数
  • 奇怪这个问题除了列出的问题之外还有其他答案

标签: c# regex string-formatting


【解决方案1】:

你可以试试这个

string test = "BE45898287271283";
test = Regex.Replace(test, ".{4}", "$0 ").Trim();

【讨论】:

    【解决方案2】:

    使用正则表达式;

    foo = Regex.Replace(foo, ".{4}", "$0 ");
    

    【讨论】:

      【解决方案3】:
      private string Group4(string s)
      {
          string output="";
          for(int i=0; i < s.Length; i+=4)
              output+=s.Substring(i, 4) + ' ';
      
          return s.TrimEnd();
      }
      

      【讨论】:

        【解决方案4】:

        试试这个正则表达式:

        [a-z\d]{4}
        
        string in="BE45898287271283";
        string out = Regex.Replace("(?i)([a-z\\d]{4})", "$1 ");
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-10-16
          • 2020-10-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多