Reputation: 1046
Can someone explain to me why the result from the following statement has a count of two an not just one?
MatchCollection matches = new Regex( ".*" ).Matches( "foo" ) ;
Assert.AreEqual( 1, matches.Count ) ; // will fail!
new Regex( ".+" ).Matches( "foo" ) ; // returns one match (as expected)
new Regex( ".*" ).Matches( "" ) ; // also returns one match
(I'm using C# of .NET 3.5)
Upvotes: 2
Views: 443
Reputation: 133995
The expression "*."
matches "foo"
at the start of the string, and an empty string at the end (position 3). Remember, *
means, "zero or more". So it matches "nothing" at the end of the string.
This is consistent. Regex.Match(string.Empty, ".*");
returns one match: an empty string.
Upvotes: 5
Reputation: 54138
Include '^' to anchor your matching expression at the start of the input string.
MatchCollection matches = new Regex( "^.*" ).Matches( "foo" ) ;
Upvotes: 0