开发者

error in regular expression for finding string $0.10/$0.20

I am trying to match on this string "$0.05/$0.10" and came up with this regular expression but I keep g开发者_Python百科etting the error newline expression in constant, where have I gone wrong? Obviously the string can change and be with or without the decimal place so this would be valid also $25/$50 or or $1/$2.

My attempt:

@"\(\$(\d+\.\d{2})\+\$(\d+\.\d{2})\));

But obviously it doesn't work!


Some things wrong with your original expression:

  • You weren't including the slash
  • The + between the two groups was odd
  • You weren't making the . optional
  • The . was matching any character instead of just .
  • Nothing was making the ".\d{2}" optional
  • It would find the match anywhere in the string (possibly correct for your use case; I've forced it to match the whole string)
  • The brackets were mismatched
  • You didn't need to put the whole thing in a capturing group; you can always match the whole pattern using group 0

Here's the fixed version:

@"^\$(\d+(?:\.\d{2})?)/\$(\d+(?:\.\d{2})?)$"

Short but complete example:

using System;
using System.Text.RegularExpressions;

class Test
{
    static void Main()
    {
        Match("$25/$2.05");
        Match("$2.05/$2.05");
        Match("$25.00/$22.05");
        Match("$25/$10");
        Match("x/$10");
        Match("$10/x");
        Match("$10$20");
    }

    private static readonly Regex Pattern = new Regex
        (@"^\$(\d+(?:\.\d{2})?)/\$(\d+(?:\.\d{2})?)$");

    static void Match(string text)
    {
        Match match = Pattern.Match(text);
        if (!match.Success) {
            Console.WriteLine("{0}: Match failed", text);
            return;
        }
        Console.WriteLine("{0}: Matched! First: {1} Second: {2}",
                          text, match.Groups[1], match.Groups[2]);
    }
}

Output:

$25/$2.05: Matched! First: 25 Second: 2.05
$2.05/$2.05: Matched! First: 2.05 Second: 2.05
$25.00/$22.05: Matched! First: 25.00 Second: 22.05
$25/$10: Matched! First: 25 Second: 10
x/$10: Match failed
$10/x: Match failed
$10$20: Match failed
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜