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.
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;
}
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,");
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 numberor
\d+
any numberto sum:
(\d+(-|/)?\d+)|\d+
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With