Skip to main content
 首页 » 编程设计

c#之如何从 C# 中的字符串中提取负整数和正整数

2024年02月05日23me-sa

当我需要显示错误信息时,代码会显示十

int _userInt = 0; 
string _checkForNumbers = "Mitchell, -10"; 
var _intInput = string.Join("", _checkForNumbers.Where(char.IsDigit)); 
int.TryParse(_intInput, out _userInt); 
if(_userInt < 0) 
{ 
  Console.WriteLine("Please only enter positive numbers"); 
  Console.ReadKey(true); 
} 
else 
{ 
  Console.Write($"{_userInt}"); 
  Console.ReadKey(true); 
} 

请您参考如下方法:

尝试用正则表达式提取数字

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; 
} 

Number extraction from strings using Regex