1

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);
mca
  • 466
  • 3
  • 11

1 Answers1

0

It looks like the "words" can contain any special characters anywhere inside the "word". In this case, you need to

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.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Thanks. Does the code also work if oldValue looks like "/Sample: Text!" ? What about 'Match whole word' and/or 'Match case' options? Thanks. – mca Mar 01 '22 at 10:45
  • @mca You can add the conditions yourself, it is basic code not related to regex already. Also, the `matchCase` is already in the code. – Wiktor Stribiżew Mar 01 '22 at 10:50