0

I've seen this topic: How to surround text with brackets using regex? but that's on ruby and I don't know the analog for C# I tried

text = System.Text.RegularExpressions.Regex.Replace(text, ' '  + SpecialWord + ' ', " \"\0\" ", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

but that didn't insert my matched word. So how do I surround my matched word with quotes?

Community
  • 1
  • 1
Bogdan Verbenets
  • 25,686
  • 13
  • 66
  • 119

2 Answers2

1

use $ instead of \ for the backreference. Also, put your special word in parenthesis and reference that sub group, otherwise, you will get the complete matched string:

text = System.Text.RegularExpressions.Regex.Replace(
                         text, "\\b("  + SpecialWord + ")\\b", " \"$1\" ", 
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

Explanation:

  • \b is a word boundary, i.e. a space, the end of the string, a full stop etc.
  • $0 will match the whole match, i.e. including the word boundary, whereas $1 matches the first sub group, i.e. the part in the parenthesis.
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
  • I don't think parentheses are necessary if you use `\b` as it's zero-width, so in this case `$0` and `$1` are identical. – Drew Noakes Apr 12 '11 at 16:08
0

Try using \b to match the word boundary, rather than a space.

You need to use $0 instead of \0 too.

text = Regex.Replace(text, @"\b" + SpecialWord + @"\b", @" ""$0"" ", RegexOptions.IgnoreCase);
Drew Noakes
  • 300,895
  • 165
  • 679
  • 742