从使用正则表达式串号提取 [英] Number extraction from strings using Regex
问题描述
我有这样的C#代码,我发现,然后根据我的需要改进,但现在我想使之成为所有数字数据类型的工作。
i have this C# code that i found and then improved upon for my needs, but now i would like to make it work for all numeric data types.
public static int[] intRemover (string input)
{
string[] inputArray = Regex.Split (input, @"\D+");
int n = 0;
foreach (string inputN in inputArray) {
if (!string.IsNullOrEmpty (inputN)) {
n++;
}
}
int[] intarray = new int[n];
n = 0;
foreach (string inputN in inputArray) {
if (!string.IsNullOrEmpty (inputN)) {
intarray [n] = int.Parse (inputN);
n++;
}
}
return intarray;
}
这非常适用于试图提取整数整数出字符串,但问题我已经是我使用正则表达式表达不设置考虑到这是消极含有小数点的一些数字或数字。我的最终目标就像我说的是做出来的这种方法要求所有数字数据类型的作品。任何人都可以帮我吗?
This works well for trying to extract whole number integers out of strings but the issue that i have is that the regex expression i am using is not setup to account for numbers that are negative or numbers that contain a decimal point in them. My goal in the end like i said is to make a method out of this that works upon all numeric data types. Can anyone help me out please?
推荐答案
可以匹配
相反,它分裂它的
public static decimal[] intRemover (string input)
{
return Regex.Matches(input,@"[+-]?\d+(\.\d+)?")//this returns all the matches in input
.Cast<Match>()//this casts from MatchCollection to IEnumerable<Match>
.Select(x=>decimal.Parse(x.Value))//this parses each of the matched string to decimal
.ToArray();//this converts IEnumerable<decimal> to an Array of decimal
}
的Array
[+ - ]
匹配 +
或 -
0或1时间
\d +
匹配1对多位数
(\.\d +)?
匹配(小数点后面1对多位数)0到1的时间
(\.\d+)?
matches a (decimal followed by 1 to many digits) 0 to 1 time
以上代码的简化形式
public static decimal[] intRemover (string input)
{
int n=0;
MatchCollection matches=Regex.Matches(input,@"[+-]?\d+(\.\d+)?");
decimal[] decimalarray = new decimal[matches.Count];
foreach (Match m in matches)
{
decimalarray[n] = decimal.Parse (m.Value);
n++;
}
return decimalarray;
}
这篇关于从使用正则表达式串号提取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!