# 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?
LVL 4
###### Who is Participating?

x

Commented:
Like this?

System.Text.RegularExpressions.Regex.Match("2", "^(11)|(22)|(33)|(44)\$").Success //Returns false

System.Text.RegularExpressions.Regex.Match("22", "^(11)|(22)|(33)|(44)\$").Success //Returns true
0

Commented:
(11|22|33|44) ?
0

Commented:
Regex r = new Regex("^(11|22|33|44)\$");
Console.WriteLine(r.IsMatch("2").ToString());
Console.WriteLine(r.IsMatch("22").ToString());
Console.WriteLine(r.IsMatch("2222").ToString());

output :

False
True
False

0

Commented:
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
0

RetiredCommented:
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
0

Commented:
You would need and extra group : "^((11)|(22)|(33)|(44))\$" to make it work.
0

Author Commented:
Thank you both.  They both are good answers though ozymandias' is a little cleaner.
0

Commented:
Whoops, thank you for the correction, ozymandias!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.