Reputation: 466
I'm looking for a regular expression to implement a search and replace method which identifies strings like "/Sample Text:" in a longer text (e.g. "This is a /Sample Text: in a sentence"), where 'Match whole word' and/or 'Match case' can be specified. I'm new to regular expressions. Thank you very much.
I tried something like below, but it is not what I expect:
var text = "This is a /Sample Text: in a sentence";
var oldValue = "/Sample Text:";
var newValue = "sample text";
var result = Regex.Replace(text, $"\\b{oldValue}{(char.IsPunctuation(newValue[newValue.Length - 1]) ? "(?!\\" + newValue[newValue.Length - 1] + ")" : string.Empty)}", newValue, RegexOptions.CultureInvariant);
Upvotes: 1
Views: 147
Reputation: 626691
It looks like the "words" can contain any special characters anywhere inside the "word". In this case, you need to
oldValue
"words"See an example C# demo:
var text = "This is a /Sample Text: in a sentence";
var oldValue = "/Sample Text:";
var newValue = "sample text";
var matchCase = RegexOptions.IgnoreCase;
var result = Regex.Replace(text, $@"(?!\B\w){Regex.Escape(oldValue)}(?<!\w\B)", newValue, matchCase);
The result
value is This is a sample text in a sentence
.
The (?!\B\w){Regex.Escape(oldValue)}(?<!\w\B)
means
(?!\B\w)
- a position that is preceded with a word boundary only if the following char is a word char{Regex.Escape(oldValue)}
- an interpolated string variable that is an escaped value of oldValue
(?<!\w\B)
- a position that is followed with a word boundary only if the preceding char is a word char.Upvotes: 0