c# - C# 在字符串中的每个数字序列后添加逗号
问题描述
我有很多带数字的字符串。我需要重新格式化字符串以在所有数字序列之后添加逗号。数字有时可能包含其他字符,包括 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;
}
解决方案
在最简单的情况下,一个简单的正则表达式就可以了:
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;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,");
推荐阅读
- google-sheets - 数组公式和MAX
- java - 有没有办法在不显示 Android 8.0 及以上版本的通知的情况下启动前台服务?
- c# - 跳过 Acr.UserDialogs 警报
- angular - 使用 ngFor 创建不同的元素类型
- php - CheckboxType 上的 Symfony 表单转换器:String to Bool
- java - Scala构造函数如何在Scala语言中转换它
- javascript - 从另一个函数中获取值
- javascript - 在 React fetch 调用中从 Node API 访问 promise 数据
- google-api - .NET 的 Google 管理员设置 API 连接
- ruby-on-rails - 安装 pundit 后尝试创建用户时出错