首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C#在字符串中的每个数字序列后面添加逗号

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

Stack Overflow用户
提问于 2018-07-19 09:10:05
回答 2查看 679关注 0票数 5

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

  • “你好1234拜拜”应该是"hello 1234,拜拜
  • "987中间文本654“应为"987,中间文本654,”。
  • "1/2是包含其他字符的数字“应该是"1/2,是包含其他字符的数字”。
  • “这也是12-3有数字”应该是“这也是12-3,有数字

谢谢大家

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

代码语言:javascript
复制
    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;
    }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-07-19 09:26:05

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

代码语言:javascript
复制
  using System.Text.RegularExpressions;

  ...

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

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

编辑:--如果您有几种格式,让我们将它们与|结合起来

代码语言:javascript
复制
  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等)相连的符号的任何组合)。

代码语言:javascript
复制
  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,");
票数 5
EN

Stack Overflow用户

发布于 2018-07-19 09:27:38

我们要用正则表达式来处理这个问题。在这里,您的模式是数字可能的字符-数字或数字:

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

  • \d+任意数

合计:

代码语言:javascript
复制
(\d+(-|/)?\d+)|\d+

Debuggex Demo

现在,我们在模式中使用Regex.Replace

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

C#演示

代码语言:javascript
复制
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},");
}

产出:

代码语言:javascript
复制
a 1, b
hello 1234, bye
987, middle text 654,
1/2, is a number containing other characters
this also 12-3, has numbers

欢迎任何评论:)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51418629

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档