Replace All Occurrences of a Pattern in a String

Problem

You want to find every time a certain pattern occurs in a string and alter the corresponding text.

Solution

Use the Regex.Replace method. You can supply either a string literal or a replacement expression for the new text.

Discussion

The Regex.Replace method has several overloads and allows a great deal of flexibility. The simplest technique is to simply replace values with a fixed string literal. For example, imagine you have a string that could contain a credit card number in a specific format. You could replace all occurrences of any credit card number, without needing to know the specific number itself, by using a regular expression.

Here’s an example that obscures phone numbers:

Dim Expression ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.