这种从字符串中提取整数的例子很常见:
string input = "10 blah 20 30 nonsense 40 50";
string[] numbers = System.Text.RegularExpressions.Regex.Split(input, @"^[\d]");
但是我如何计算带小数点的数字呢?
例如
string input = "10 blah 20 30 nonsense 40.5 50"
配合上面的正则表达式使用,不出所料,将小数点后的40和5拆分成了numbers数组的不同元素。
出于天真,我认为下面的方法可行:
string[] numbers = System.Text.RegularExpressions.Regex.Split(input, @"^[\d\.]");
但这会导致小数点被拆分到它自己的数组元素中。
这看起来应该很简单,但我尝试了各种正则表达式都没有成功。我正在撕扯我的头发 - 非常感谢任何帮助!
最佳答案
请记住,使用 Regex.Split(input, @"[^\d.]+");
,您将得到误报(对于像 non. sense 或 50.6.8) => 您必须过滤掉值为“.”的结果。在其中。
您也可以使用 Matches 方法代替 Split。
MatchCollection mc = Regex.Matches(input, @"\d+(?:\.\d+)?");<br />
string[] numbers = (from Match m in mc select m.Value).ToArray();
关于c# - 如何让 RegEx.Split 从字符串中提取一系列包含小数点的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3147880/