Tuesday, December 8, 2009

Regex.IsMatch always returning true?

The following code was failing:

public void ShouldNotMatchInvalidCharacters()
Regex regex = null;
string invalidString = null;
bool result = false;

Story.WithScenario("matching invalid characters")
.Given("a regex expression",
() => regex = new Regex(@"[0-9]*\.{0,1}[0-9]*"))
.And("an invalid string",
()=> invalidString = "a")
.When("we check whether we have a match",
() => result = regex.IsMatch(invalidString))
.Then("the match should fail",
() => Assert.IsFalse(result));

It turns out it was matching on the empty string. I couldn’t think why on earth it was doing this. A bit of googling and the correct way to match on an entire string is to specify the start and end of the string in the regex.


The test now goes green!

No comments:

Post a Comment