2

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

我的问题是我只希望字符串中以“+”或“-”为前缀的小数。

这是我目前的解决方案:

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

由于我不太了解正则表达式,因此我需要一些更合适的模式的帮助。

4

2 回答 2

2

我从Splitting 非数字切换到Matching 数字。这会得到你想要的结果:

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));
}
于 2013-10-22T20:50:59.087 回答
2

尝试(\+|\-)[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)
  {

  }
}
于 2013-10-22T20:51:25.900 回答