0

I'm new to regex and I don't seem te find my way out with those patterns. I'm trying to match the punctuation in a sentence (quotation marks and question mark) with no success.

Here is my code:

string sentence = "\"This is the end?\"";
string punctuation = Regex.Match(sentence, "[\"?]").Value;

What am I doing wrong here? I'd expect the console to display "?", however, it shows me a double quote.

TheThugger
  • 23
  • 6

2 Answers2

3

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}.

p.s.w.g
  • 136,020
  • 27
  • 262
  • 299
2

You need to call Matches instead of Match.

Example:

string sentence = "\"This is the end?\"";
var matches = Regex.Matches(sentence, "[\"?]");
var punctuationLocations = string.Empty;
foreach(Match match in matches)
{
    punctuationLocations += match.Value + " at index:" + match.Index + Environment.NewLine;
}

// punctuationLocations:
//   " at index:0
//   ? at index:16
//   " at index:17
JGriffin
  • 21
  • 4