Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Add comma after every number sequence in string

Tags:

string

c#

I have many strings with numbers. I need to reformat the string to add commas after all number sequences. Numbers may sometimes contain other characters including 12-3 or 12/4 e.g.

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

Thank you all

EDIT: My example does not account for any special characters. I didn't include it originally as I thought I'd get a fresh perspective if someone can do this more efficiently - my bad!

    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;
    }
like image 654
justlearning Avatar asked Jul 19 '18 09:07

justlearning


2 Answers

An easy regular expression will do in the simplest case:

  using System.Text.RegularExpressions;

  ...

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

we are looking for numbers (which are 1 or more digits - [0-9]+) and replace entire match $0 into match with comma: $0,.

Edit: If you have several formats let's combine them with |:

  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,"); 

Edit 2: if we want to generalize (i.e. "other numbers" are any combination of numbers joined with any symbol which is not alphamumeric or white space, e.g. 12;45, 123.78, 49?466 etc)

  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,");
like image 128
Dmitry Bychenko Avatar answered Oct 29 '22 10:10

Dmitry Bychenko


We are going to use regex for this. Here your pattern is number-possible character-number or number:

  • \d+ any number
  • (-|/)? possible - or /
  • \d+ any number

or

  • \d+ any number

to sum:

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

Regular expression visualization

Debuggex Demo

Now, we use Regex.Replace with our pattern.

Regex.Replace

In a specified input string, replaces all strings that match a regular expression pattern with a specified replacement string.

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},");
}

output:

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

Any comment is welcome :)

like image 20
aloisdg Avatar answered Oct 29 '22 09:10

aloisdg