Regex.Matches, quote. In C# programs, strings sometimes have quoted values—it is often useful to extract these values. This helps us parse text or code such as SQL statements.
Program uses. We can use Regex for an efficient and simple way to do this. We handle quoted values with Regex. Some syntax, like escaped values, are harder to support.
Example. We match values within quotes using Regex.Matches. To use Regex.Matches, pass it a pattern—this specifies the group you are capturing. Our group here is surrounded by single quotes.
Part 4 The fields we captured are displayed to the console. You can see there are 5 output fields. This is our required result.
using System;
using System.Text.RegularExpressions;
// Part 1: the input string.
string line = "INSERT INTO country VALUES ('BH','BAHRAIN','Bahrain','BHR','048');";
// Part 2: match all quoted fields.
MatchCollection col = Regex.Matches(line, @"'(.*?)'");
// Part 3: copy groups to a string array.
string[] fields = new string[col.Count];
for (int i = 0; i < fields.Length; i++)
{
fields[i] = col[i].Groups[1].Value; // (Index 1 is the first group)
}
// Part 4: display the fields.
foreach (string field in fields)
{
Console.WriteLine(field);
}BH
BAHRAIN
Bahrain
BHR
048
Performance. Regular expressions do not result in optimal execution time. Therefore, in performance-critical situations, you will want a more complex parser.
But Often when dealing with text data, we don't require heavy performance tuning. Consider compiled Regexes.
A summary. We extracted quoted values from an input string using Regex.Matches. This style of code is sometimes useful to developers working with regular expressions.
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.
This page was last updated on Nov 17, 2023 (edit).