C#在字符串中的每个数字序列后添加逗号

时间:2018-07-19 09:10:06

标签: c# string

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

  • “你好1234再见”应该是“ 你好1234再见
  • “ 987中间文字654”应为“ 987,中间文字654
  • “ 1/2是包含其他字符的数字”应为“ 1/2,是一个 包含其他字符的数字
  • “这也是12-3,有数字”应该为“ 这也是12-3,有数字” 数字

谢谢大家

编辑: 我的示例没有考虑任何特殊字符。我最初没有包括它,因为我认为如果有人可以更有效地做到这一点,我将获得全新的视角-我的糟糕!

    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;
    }

2 个答案:

答案 0 :(得分:5)

最简单的情况下,将使用简单的正则表达式

  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:,如果我们想泛化(即“其他数字”是数字的任何组合,并加上非字母数字或空格的任何符号,例如{ {1}},12;45123.78等)

49?466

答案 1 :(得分:1)

我们将为此使用正则表达式。这里的模式是数字可能的字符数或数字:

  • \d+任何数字
  • (-|/)?-或/
  • \d+任何数字

  • \d+任何数字

总和:

(\d+(-|/)?\d+)|\d+

Regular expression visualization

Debuggex Demo

现在,我们将Regex.Replace与我们的模式一起使用。

  

Regex.Replace

     

在指定的输入字符串中,将所有与正则表达式模式匹配的字符串替换为指定的替换字符串。

C# Demo

public static void Main()
{
    Console.WriteLine(AddComma("a 1 b"));
    Console.WriteLine(AddComma("hello 1234 bye"));
    Console.WriteLine(AddComma("987 middle text 654"));
    Console.WriteLine(AddComma("1/2 is a number containing other characters"));
    Console.WriteLine(AddComma("this also 12-3 has numbers"));
}

public static string AddComma(string input)
{
    return Regex.Replace(input, @"(\d+(-|/)?\d+)|\d+", m => $"{m.Value},");
}

输出:

a 1, b
hello 1234, bye
987, middle text 654,
1/2, is a number containing other characters
this also 12-3, has numbers

欢迎任何评论:)