从字符串中查找并提取所有数字

3

我有一个字符串:Hello I'm 43 years old, I need 2 burgers each for 1.99$。我需要解析它并将其中所有数字作为double返回。因此,该函数应该返回一个值数组:43,2,1.99。在C ++中,我必须自己编写代码,但是C#具有Regex,我认为它可能在这里有帮助:

String subjectString = "Hello I'm 43 years old, I need 2 burgers each for 1.99$";
resultString = Regex.Match(subjectString, @"\d+").Value;
double result = double.Parse(resultString);

在此之后,resultString是"43",而result43.0。如何解析字符串以获取更多数字?


就我而言,这个问题有一个更完整的答案,所以做出决定。 - Netherwire
3个回答

5

您的正则表达式需要更加复杂,才能包含小数:

\d+(\.\d+)?

接下来你需要获取多个匹配项:

MatchCollection mc = Regex.Matches(subjectString, "\\d+(\\.\\d+)?");
foreach (Match m in mc)
{
    double d = double.Parse(m.Groups[0].Value);
}

Here is an example.


如有需要,请务必检查本地化问题。并非每个人都使用相同的小数分隔符。 - GaussZ
@GaussZ 你是指点号还是逗号? - Netherwire
@GaussZ 很好的观点。是的,可能是点或逗号。另外,您的输入也需要注意千位分隔符吗? - CodingIntrigue
@RomanChehowsky 是的。通常,千位分隔符是相反的(逗号用于点小数分隔符,反之亦然)。 - GaussZ
@GaussZ 非常感谢,它完美地运行了。 - Netherwire

2

尝试使用以下正则表达式:

-?[0-9]+(\.[0-9]+)?

然后使用 Regex.Matches 并迭代返回的匹配项。


1
你应该使用 Matches 方法来获取匹配项的集合。此外,你需要在正则表达式中添加句点。
String subjectString = "Hello I'm 43 years old, I need 2 burgers each for 1.99$";
var matches = Regex.Matches(subjectString, @"\d+(\.\d+)?");

for (int i = 0; i < matches.Count; i++ )
{
    double d = double.Parse(matches[i].Value);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接