在以“+”或“-”开头的字符串中查找十进制数

本文关键字:字符串 查找 十进制数 在以 开头 | 更新日期: 2023-09-27 18:36:38

我想从从远程服务收到的字符串中获取一些十进制数字。

我的问题是我只想要以"+"或"-"为前缀的字符串中的小数。

这是我当前的解决方案:

string text = "+123.23 foo 456.34 bar -789.56";
List<string> decimals = Regex.Split(text, @"[^0-9'.]+").Where(
                             c => c != "." && c.Trim() != string.Empty).ToList();
foreach (var str in decimals)
{
    Console.WriteLine(str); 
}
// Output:
//           
// 123.23 
// 456.34
// 789.56
//
// Desired output:
//
// 123.23
// -789.56

由于我不太了解正则表达式,因此我希望获得更合适的模式的帮助。

在以“+”或“-”开头的字符串中查找十进制数

我从对非数字的Split切换到Match数字。这将获得您想要的结果:

string text = "+123.23 foo 456.34 bar -789.56";
List<string> decimals = Regex.Matches(text, @"[+'-][0-9]+('.[0-9]+)?")
                          .Cast<Match>().Select(m => m.Value).ToList();
foreach (var str in decimals)
{
    Console.WriteLine(decimal.Parse(str));
}

尝试('+|'-)[0-9'.]+

string strRegex = @"('+|'-)[0-9'.]+";
Regex myRegex = new Regex(strRegex);
string strTargetString = @"+123.23 foo 456.34 bar -789.56";
foreach (Match myMatch in myRegex.Matches(strTargetString))
{
  if (myMatch.Success)
  {
  }
}