从字符串中获取多个数字
问题描述:
我有像
AS_!SD 2453iur ks@d9304-52kasd
AS_!SD 2453iur ks@d9304-52kasd
我需要获取字符串的 2 个第一个数字:
I need to get the 2 frist numbres of the string:
对于这种情况将是:2453
和 9304
for that case will be:
2453
and 9304
我在字符串中没有任何分隔符来尝试拆分,并且数字和字符串的长度是可变的,我在 WPF 中使用 C# 框架 4.0.
I don't have any delimiter in the string to try a split, and the length of the numbers and string is variable, I'm working in C# framework 4.0 in a WPF.
感谢您的帮助,并为我的英语不好
thanks for the help, and sorry for my bad english
答
此解决方案将取两个前数字,每个数字可以有任意位数
This solution will take two first numbers, each can have any number of digits
string s = "AS_!SD 2453iur ks@d9304-52kasd";
MatchCollection matches = Regex.Matches(s, @"\d+");
string[] result = matches.Cast<Match>()
.Take(2)
.Select(match => match.Value)
.ToArray();
Console.WriteLine( string.Join(Environment.NewLine, result) );
将打印
2453
9304
您可以通过 result.Select(int.Parse).ToArray();