Reputation: 861
I have a sentence, "Name # 2" ,
I need to replace '#', with "No.",
Final sentence needs to be "Name No. 2".
Code -
string sentence = Regex.Replace("Name # 2", "\\#\\b", "No.");
Apparently the Regex.Replace fails to replace '#' with 'No', is there a correct way to approach the problem, via a regular expression. thanks The reason I am looking for a regex pattern is because there is a generic code which executes which looks something like below
string pattern = string.Format(@"\b{0}\b", context);
sentence = System.Text.RegularExpressions.Regex.Replace(sentence, pattern, suggestion);
context - "#"
sentence - "Name # 2"
suggestion - "No."
Expected sentence - "Name No. 2"
Actual sentence - "Name # 2"
context - "were"
sentence - "He were going"
suggestion - "was"
Expected sentence - "He was going"
Actual sentence - "He was going"
context - "a"
sentence - "He was at a point in time going."
suggestion - "z"
Expected sentence - "He was at z point in time going"
Upvotes: 5
Views: 519
Reputation: 626689
The current regex won't match if the #
is preceded with a word char, a letter, digit or an underscore. That happens because a word boundary meaning is context dependent.
Replace it with any of the fixes below:
string pattern = string.Format(@"(?<!\w){0}(?!\w)", Regex.Escape(context));
^^^^^^ ^^^^^^
The (?<!\w)
and (?!\w)
are context-independent and will match a word if not preceded/followed with a word char.
Or, use
string pattern = string.Format(@"(?<!\S){0}(?!\S)", Regex.Escape(context));
to only match a word inside whitespace(s) as (?<!\S)
negative lookbehind requires the whitespace or the start of the string before the "word", and the negative lookahead (?!\S)
requires the end of string or whitespace after the "word".
Note that Regex.Escape
is a must when you deal with user-input/dynamic pattern building and need to use a literal string inside the regex pattern. It will escape all the special chars (like ?
, +
, etc.) that could ruin the pattern otherwise.
Upvotes: 6
Reputation: 2111
You can try:
string sentence = Regex.Replace("Name # 2", "#", "No.");
# does not have to escaped, therefore there is no need for the backslashes.
Upvotes: 3
Reputation: 6785
Using Regex you can do it like so:
Regex.Replace("Name # 2", "#", "No.")
Or just a plain old string.Replace:
"Name # 2".Replace("#", "No.");
Upvotes: 2