我有很多带数字的字符串。我需要重新格式化字符串以在所有数字序列之后添加逗号。数字有时可能包含其他字符,包括12-3或12/4。
谢谢大家
编辑:--我的示例不考虑任何特殊字符。我不包括它最初,因为我认为我会得到一个新的视角,如果有人可以更有效地这样做-我的错!
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;
}发布于 2018-07-19 09:26:05
在最简单的情况下,一个简单的正则表达式就可以了。
using System.Text.RegularExpressions;
...
string source = "hello 1234 bye";
string result = Regex.Replace(source, "[0-9]+", "$0,");我们正在寻找数字(这是一个或更多的数字- [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;45、123.78、49?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-19 09:27:38
我们要用正则表达式来处理这个问题。在这里,您的模式是数字可能的字符-数字或数字:
\d+任意数(-|/)?可能-或/\d+任意数或
\d+任意数合计:
(\d+(-|/)?\d+)|\d+

现在,我们在模式中使用Regex.Replace。
Regex.Replace 在指定的输入字符串中,用指定的替换字符串替换与正则表达式模式匹配的所有字符串。
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欢迎任何评论:)
https://stackoverflow.com/questions/51418629
复制相似问题