Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Search and replace method using regular expressions

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);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading