If you want to match all quotation marks and question marks as your question states, then your pattern is okay. The problem is that Regex.Match
will only return the first match it finds. From MSDN:
Searches the input string for the first occurrence of the specified regular expression...
You probably want to use Matches
:
string sentence = "\"This is the end?\"";
MatchCollection allPunctuation = Regex.Matches(sentence, "[\"?]");
foreach(Match punctuation in allPunctuation)
{
Console.WriteLine("Found {0} at position {1}", punctuation.Value, punctuation.Index);
}
This will return:
Found " at position 0
Found ? at position 16
Found " at position 17
I'd also point out that if you truly want to match all punctuation characters, including things like 'French' quotes («
and »
), 'smart' quotes (“
and ”
), inverted question marks (¿
), and many others, you can use Unicode Character categories with a pattern like \p{P}
.