Regex string replacement pattern

I have a sentence, "Name # 2",

I need to replace "#" with "No",

The final sentence should be "Name No. 2".

Code -

string sentence = Regex.Replace("Name # 2", "\\#\\b", "No."); 

Apparently, Regex.Replace cannot replace '#' with 'No', is there a proper way to approach the problem through regex. thanks The reason I'm looking for a regex pattern is because common code is being executed that looks something like this:

  string pattern = string.Format(@"\b{0}\b", context); sentence = System.Text.RegularExpressions.Regex.Replace(sentence, pattern, suggestion); 

context - "#"

offer - "Name No. 2"

the sentence is "No."

Expected Proposal - "Name No. 2"

Actual offer - "Name No. 2"

context - were

sentence - "He walked"

the sentence was

Expected Proposal - "He Walked"

Actual sentence - "He walked"

context - "a"

sentence - "He was at a time."

sentence - "z"

Expected Proposal - "He was at a time"

+5
source share
4 answers

The current regular expression will not match if # is preceded by a char, letter, number, or underscore. This is because the meaning of the word boundary depends on the context.

Replace it with any of the following fixes:

 string pattern = string.Format(@"(?<!\w){0}(?!\w)", Regex.Escape(context)); ^^^^^^ ^^^^^^ 

(?<!\w) and (?!\w) do not depend on the context and will correspond to the word if you do not precede / follow the word char.

Or use

 string pattern = string.Format(@"(?<!\S){0}(?!\S)", Regex.Escape(context)); 

to match only words inside spaces, since (?<!\S) negative lookbehind requires a space or the beginning of a line before a word, and a negative lookahead (?!\S) requires a line ending or a space after a "word".

Note that Regex.Escape is required when you are dealing with creating a custom input / dynamic pattern and must use a literal string inside the regular expression pattern. It will avoid all special characters (e.g. ? , + , Etc.), which may ruin the pattern otherwise.

+6
source
 string test = "Name # 2"; test = test.Replace("#", "No."); 
+4
source

You can try:

 string sentence = Regex.Replace("Name # 2", "#", "No."); 

# no need to escape, so no backslashes are needed.

+3
source

With Regex, you can do it like this:

 Regex.Replace("Name # 2", "#", "No.") 

Or just a plain old line. Replace:

 "Name # 2".Replace("#", "No."); 
+2
source

Source: https://habr.com/ru/post/1260075/


All Articles