how to surround a word using System.Text.RegularExpressions.Regex
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 w开发者_StackOverflowith quotes?
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.
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);
精彩评论