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?
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?
(11|22|33|44) ?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Expert1701 :
Regex.Match("2", "^(11)|(22)|(33)|(44)$").S uccess; <-- returns false
Regex.Match("22", "^(11)|(22)|(33)|(44)$").S uccess; <-- returns true
Regex.Match("2222", "^(11)|(22)|(33)|(44)$").S uccess; <-- returns true
Regex.Match("12344", "^(11)|(22)|(33)|(44)$").S uccess; <-- returns true
Regex.Match("2", "^(11)|(22)|(33)|(44)$").S
Regex.Match("22", "^(11)|(22)|(33)|(44)$").S
Regex.Match("2222", "^(11)|(22)|(33)|(44)$").S
Regex.Match("12344", "^(11)|(22)|(33)|(44)$").S
Hi CBeach1980;
Here is some sample code to do what you want.
using System.Text.RegularExpress ions;
private void button2_Click(object sender, EventArgs e)
{
string possiblevalues = "11,22,33,44";
MessageBox.Show(ValidateNu mber(possi blevalues, 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
Here is some sample code to do what you want.
using System.Text.RegularExpress
private void button2_Click(object sender, EventArgs e)
{
string possiblevalues = "11,22,33,44";
MessageBox.Show(ValidateNu
}
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.
ASKER
Thank you both. They both are good answers though ozymandias' is a little cleaner.
Whoops, thank you for the correction, ozymandias!