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.
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.
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 ModuleBH
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.
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.