miasbeck
miasbeck

Reputation: 1046

C# Regex.Matches returns too many matches?

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

Answers (2)

Jim Mischel
Jim Mischel

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

Steve Townsend
Steve Townsend

Reputation: 54138

Include '^' to anchor your matching expression at the start of the input string.

MatchCollection matches = new Regex( "^.*" ).Matches( "foo" ) ;

Upvotes: 0

Related Questions