-1

What will be the regular expression to fined out 4.55$, 5$, $45, $7.86 in a string?

I used @"(?<=\$)\d+(\.\d+)?" but it only finds $45, $7.86.

4

4 回答 4

2

这似乎工作正常:

@"((?<=\$)\d+(\.\d+)?)|(\d+(\.\d+)?(?=\$))"

代码示例:

string source = "4.55$, 5$, $45, $7.86";
string reg = @"((?<=\$)\d+(\.\d+)?)|(\d+(\.\d+)?(?=\$))";
MatchCollection collection = Regex.Matches(source, reg);
foreach (Match match in collection)
{
    Console.WriteLine(match.ToString());
}
于 2012-05-24T11:13:13.363 回答
0

这有点笨拙,但这是另一个可能对您有用的表达式(带有一些解释性代码):

string strRegex = @"\$(?<Amount>\d[.0-9]*)|(?<Amount>\d[.0-9]*)\$";
Regex myRegex = new Regex(strRegex);
string strTargetString = @"4.55$, 5$, $45, $7.86 ";

foreach (Match myMatch in myRegex.Matches(strTargetString))
{
    if (myMatch.Success)
    {
        //Capture the amount
        var amount = myMatch.Groups["Amount"].Value;
    }
}

实际上,它所做的是定义在金额开头或结尾处匹配$的交替方式。

我已经使用RegexHero对此进行了测试。

于 2012-05-24T10:36:44.920 回答
-1

我会在字符串中使用类似下面的表达式“Globaly”

string expression = @"(\$\d(\.\d*)?|\d(\.\d*)?\$)";
于 2012-05-24T10:54:35.090 回答
-4

在字符串中罚款 4.55$、5$、$45、$7.86 的正则表达式是什么?

找到4.55$, 5$, $45, $7.86你可以使用4.55\$, 5\$, \$45, \$7.86.

编辑一些评论员担心人们会在不理解的情况下使用它。我提供了一个例子,这样就可以理解。

using System;
using System.Text.RegularExpressions;

public class Test
{
    public static void Main()
    {
        string search = @"The quick brown fox jumped over 4.55$, 5$, $45, $7.86";
        string regex = @"4.55\$, 5\$, \$45, \$7.86";

        Console.WriteLine("Searched and the result was... {0}!", Regex.IsMatch(search, regex));
    }
}

输出是Searched and the result was... True!

于 2012-05-24T09:23:47.863 回答