Regex.Matches
, quoteIn 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
usesWe 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.
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.
string
looks like an SQL query. We can see values are contained in parentheses and quotes.MatchCollection
is populated from the pattern specified. We use parentheses to indicate we want to capture values within quotes.string
array is useful if you want to copy the fields to a new array.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
Regular expressions do not result in optimal execution time. Therefore, in performance-critical situations, you will want a more complex parser.
We extracted quoted values from an input string
using Regex.Matches
. This style of code is sometimes useful to developers working with regular expressions.