首页 > 解决方案 > C# 在字符串中的每个数字序列后添加逗号

问题描述

我有很多带数字的字符串。我需要重新格式化字符串以在所有数字序列之后添加逗号。数字有时可能包含其他字符,包括 12-3 或 12/4,例如

谢谢你们

编辑: 我的示例不考虑任何特殊字符。我最初没有包括它,因为我认为如果有人能更有效地做到这一点,我会得到一个全新的视角——我的错!

    private static string CommaAfterNumbers(string input)
    {
        string output = null;

        string[] splitBySpace = Regex.Split(input, " ");
        foreach (string value in splitBySpace)
        {
            if (!string.IsNullOrEmpty(value))
            {
                if (int.TryParse(value, out int parsed))
                {
                    output += $"{parsed},";
                }
                else
                {
                    output += $"{value} ";
                }
            }
        }
        return output;
    }

标签: c#string

解决方案


在最简单的情况下,一个简单的正则表达式就可以了:

  using System.Text.RegularExpressions;

  ...

  string source = "hello 1234 bye"; 
  string result = Regex.Replace(source, "[0-9]+", "$0,");

我们正在寻找数字(1个或多个数字 - [0-9]+)并将整个匹配替换$0为逗号匹配:$0,

编辑:如果您有多种格式,让我们将它们与|

  string source = "hello 1234 1/2 45-78 bye";

  // hello 1234, 1/2, 45-78, bye
  string result = Regex.Replace(source,
    @"(?:[0-9]+/[0-9]+)|(?:[0-9]+\-[0-9]+)|[0-9]+"
     "$0,"); 

编辑2:如果我们想概括(即“其他数字”是与任何非字母数字或空格符号连接的数字组合,例如12;45123.7849?466

  string source = "hello 123 1/2 3-456 7?56 4.89 7;45 bye";

  // hello 123, 1/2, 3-456, 7?56, 4.89, 7;45, bye
  string result = Regex.Replace(source,
    @"(?:[0-9]+[\W-[\s]][0-9]+)|[0-9]+"
     "$0,");

推荐阅读