Reputation: 13621
Match match = Regex.Match("555-5555555", "^(\\d{3}\\-?\\d{3}\\-?\\d{4})$", RegexOptions.None);
it["Should match"] = () => match.Success.should_be_true();
The above should match i believe. I require the numbers, but leaving the hyphens as optional. However, the above returns false and fails the test.
Edit
Accepted answer as Darin is right, something is wrong with my test scope. Here's my updated code that passes:
Match match;
void describe_example()
{
context["goodregex"] = () =>
{
before = () => match = Regex.Match("555-5555555", "^(\\d{3}\\-?\\d{3}\\-?\\d{4})$", RegexOptions.None);
it["Should match"] = () => match.Success.should_be_true();
};
context["badregex"] = () =>
{
before = () => match = Regex.Match("555-5525-5555", "^(\\d{3}\\-?\\d{3}\\-?\\d{4})$", RegexOptions.None);
it["Should not match"] = () => match.Success.should_be_false();
};
}
Upvotes: 0
Views: 730
Reputation: 1752
Your RegEx works correctly on my machine. For regex that validate different types of telephone numbers please look here (you could compare with your needs and choose the most appropriate one):
http://www.regexlib.com/Search.aspx?k=phone&AspxAutoDetectCookieSupport=1
Upvotes: 1
Reputation: 1039438
The following program prints true:
class Program
{
static void Main()
{
var match = Regex.Match("555-5555555", "^(\\d{3}\\-?\\d{3}\\-?\\d{4})$", RegexOptions.None);
Console.WriteLine(match.Success);
}
}
I guess you are having some scoping issue in your unit test where the match
variable is being modified when running tests concurrently.
Upvotes: 1
Reputation: 41767
The regex looks fine to me. And in fact match.Success
is true on my machine. I'd probably rewrite the regex as:
"^(\\d{3}\\-?){2}\\d{4}$"
However, that's only a matter of preference.
Upvotes: 0