contactmatt
contactmatt

Reputation: 18610

Match regex pattern for array of dollar denominations

A user can input the following: I $1 $5 $10 $20 $50 $100

Ordering is not important, and I'm not worried if they enter a denomination more than once (i.e. I $1 $5 $5). The beginning of the input starts with a capital "I" followed by a space.

What I have so far is this but I'm not too familiar with regex and cannot make it match my desired pattern:

^I\s(\$1|\$[5]|\$10|\$20|\$50|\$[100])$

I want to validate that the input is valid.

Upvotes: 2

Views: 342

Answers (3)

Ilya Ivanov
Ilya Ivanov

Reputation: 23626

The idea is to expect after I either a space, or a $1, $5, etc...

string[] options = 
            {
                "I $1 $5 $10 $20 $50 $100",
                "I $1 $5 $5",
                "I wrong",
                "$1 $5 $5",
                "I",
                "I ",
            };
var reg = new Regex(@"^I\s(\s|(\$1|\$5|\$10|\$20|\$50|\$100))*$");

foreach (var option in options)
{
    var status = reg.Match(option).Success ? "valid" : "invalid";
    Console.WriteLine("{0} -> is {1} (length: {2})", option.PadRight(25), status, option.Length);
}

prints:

I $1 $5 $10 $20 $50 $100  -> is valid (length: 24)
I $1 $5 $5                -> is valid (length: 10)
I wrong                   -> is invalid (length: 7)
$1 $5 $5                  -> is invalid (length: 8)
I                         -> is invalid (length: 1)
I                         -> is valid (length: 2)

Upvotes: 0

Steve P.
Steve P.

Reputation: 14699

regex = "^I(?:\s\$(?:10?0?|20|50?))+$"

^I says begins with 'I'
(?:\s\$ says group, but do not capture whitespace followed by a '$' followed by the next expression
(?:10?0?|20|50?) says group, but do not capture 1 followed by up to two 0's or 20 or 5 followed by up to one 0
+ says at least one match
$ says ends with the preceding

Upvotes: 2

lordkain
lordkain

Reputation: 3109

You use regex with check on digits

I[\s\$\d]*$

Howeever I would suggest u use String.Split(' ', input) and go from there

Upvotes: -1

Related Questions