Why does 'Zero Or One Time'(?) quantifier return the correct result and an emty string

I have this pattern here:

string pattern = @".?";
string input = "o";

foreach (Match match in Regex.Matches(input, pattern))
  Console.WriteLine("<{0}> found at position {1}.", match.Value, match.Index);

For some reason it returns the following:

<o> found at position 0.
<> found at position 1.

Why does it return <> found at position 1. ?
I mean It already returned the <o> so it should not return anythiung else.

>Solution :

Well, pattern



any symbol (.) zero or one times (?)

In your case – "o" – you have 2 matches:

|| <- position 1: any symbol zero times (empty string)
| <-- position 0: any symbol one time ('o')

Leave a Reply