5

我有很多带数字的字符串。我需要重新格式化字符串以在所有数字序列之后添加逗号。数字有时可能包含其他字符,包括 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;
    }
4

2 回答 2

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:如果我们想概括(即“其他数字”是与任何非字母数字或空格符号连接的数字组合,例如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,");
于 2018-07-19T09:26:05.093 回答
1

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

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

或者

  • \d+任何数字

总结:

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

正则表达式可视化

调试演示

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

正则表达式替换

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

C# 演示

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

欢迎任何评论:)

于 2018-07-19T09:27:38.507 回答