O'Reilly logo

Microsoft® Visual Basic® .NET Programmer's Cookbook by Matthew MacDonald

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required