Link to home
Start Free TrialLog in
Avatar of CBeach1980
CBeach1980

asked on

Regular Expression for numbers

My problem seems simple but the solution has evaded me so far.  I want to validate that a number is in a set of possible numbers.

For example:
value = 22
possible values = (11,22,33,44)

Can anyone provide a regular expression that will validate 22 but not 2 or 222?  Does that make sense?
Avatar of ozymandias
ozymandias
Flag of United Kingdom of Great Britain and Northern Ireland image

(11|22|33|44) ?
ASKER CERTIFIED SOLUTION
Avatar of Expert1701
Expert1701

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Expert1701 :

Regex.Match("2", "^(11)|(22)|(33)|(44)$").Success;           <-- returns false
Regex.Match("22", "^(11)|(22)|(33)|(44)$").Success;         <-- returns true
Regex.Match("2222", "^(11)|(22)|(33)|(44)$").Success;      <-- returns true
Regex.Match("12344", "^(11)|(22)|(33)|(44)$").Success;    <-- returns true
Avatar of Fernando Soto
Hi CBeach1980;

Here is some sample code to do what you want.

using System.Text.RegularExpressions;

        private void button2_Click(object sender, EventArgs e)
        {
            string possiblevalues = "11,22,33,44";
            MessageBox.Show(ValidateNumber(possiblevalues, textBox1.Text).ToString());
        }

        private Boolean ValidateNumber(string findin, string num)
        {
            num = num.Trim();
            try
            {
                int digits = Convert.ToInt32(num);
            }
            catch
            {
                return false;
            }

            return Regex.IsMatch(findin, @",?\s*(" + num + @")\s*,?");
        }


Fernando
You would need and extra group : "^((11)|(22)|(33)|(44))$" to make it work.
Avatar of CBeach1980
CBeach1980

ASKER

Thank you both.  They both are good answers though ozymandias' is a little cleaner.
Whoops, thank you for the correction, ozymandias!