Developer

Replace all occurrences of a pattern in a string with VB.NET

The Regex.Replace method allows you to replace a pattern in a string with a fixed string literal. This VB.NET tip describes how developers can use this method.

When you need to find a certain pattern of a string and modify the text to hide the contents, you can utilize VB.NET's Regex.Replace method. Regex.Replace is a very efficient way to replace values. It allows you to replace the string with a fixed string literal, and it provides a number of overloads that give developers the freedom to fully utilize this method.

In the example in Listing A, I look for a way to find a particular pattern in a string and replace it; supply a string literal that should replace the text in the example; and explore obscuring birth date data in a string with the generic text XX/XX/XXXX.

Notes about the code

I create the String variable, strTxt, to hold the value of the original text. I also define the Regex variable, rgxExp, to hold the value of the expression of the fixed string literal. I then set the text of the strTxt to some text that utilizes the data, which I plan to hide from display and utilize the Regex.Replace method to replace all occurrences of the dates of birth (DOB) data with the expression specified. The result is the text that shows the original text except for showing XX/XX/XXXX whenever a DOB format is met. I then display the resulting string in a message box.

Miss a tip?

Check out the Visual Basic archive, and catch up on the most recent editions of Irina Medvinskaya's column.

Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically sign up today!

Editor's Picks

Free Newsletters, In your Inbox