Regex.Matches
, quoteRegex.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.
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
We first import System.Text.RegularExpressions
. This program matches all the quoted values within the example value string
.
Regex.Matches
with a pattern that means we want zero or more characters inside single quotes.Match
instances that are found on the MatchCollection
returned by the Matches()
method.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
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.