Home
VB.NET
Regex.Matches Quote Example
This page was last reviewed on Nov 17, 2023.
Dot Net Perls
Regex.Matches, quote. Regex.Matches can handle quoted data. We parse a String containing fields inside quotes in VB.NET—special care must be taken with the expression pattern.
When parsing some files, we may have to deal with quoted values. We show an example of parsing a textual list. Some clever code to detect the quotes is helpful.
Regex.Matches
Required input and output. Consider this example string that contains the word "Bahrain" in single quotes. We want to extract the terms, eliminating the surrounding characters.
Input: ('BH','BAHRAIN','Bahrain','BHR','048')
BH BAHRAIN Bahrain BHR 048
Example. We first import System.Text.RegularExpressions. This program matches all the quoted values within the example value string.
Step 1 We call Regex.Matches with a pattern that means we want zero or more characters inside single quotes.
Step 2 We loop through the Match instances that are found on the MatchCollection returned by the Matches() method.
Step 3 We access the first group of each Match, and then print its value. This String could be stored in a List or used elsewhere.
Imports System.Text.RegularExpressions Module Module1 Sub Main() Dim value As String = "('BH','BAHRAIN','Bahrain','BHR','048')" ' Step 1: match data between single quotes hesitantly. Dim result As MatchCollection = Regex.Matches(value, "'(.*?)'") ' Step 2: loop through Matches. For Each m As Match In result ' Step 3: access first Group and its value. Dim group = m.Groups(1) Console.WriteLine(group.Value) Next End Sub End Module
BH BAHRAIN Bahrain BHR 048
Some notes. There are alternative methods you can use to accomplish this same task. A For-loop that appends the substrings to a List could work, or Regex.Split could be called.
For
Regex.Split
With a Regex, we can extract substrings from inside certain characters such as quotes. The Regex pattern can be changed for each program's needs as well.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 17, 2023 (new).
Home
Changes
© 2007-2024 Sam Allen.