HomeSearch

C# Regex.Matches Quote Example

This C# example uses the Regex.Matches method on quoted string data.
Regex.Matches, quote. Strings sometimes have quoted values. It is often useful to extract these values. This helps parse text or code such as SQL statements. We can use Regex for an efficient and simple way to do this. We handle quoted values with Regex.
Input: ('BH','BAHRAIN','Bahrain','BHR','048') Fields: BH BAHRAIN Bahrain BHR 048
Example. There is an easy way to match values within single quotes or double 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 quote characters.Regex.Matches

MatchCollection: This is populated from the pattern specified. We use parentheses to indicate we want to capture values within quotes.

Question mark: This means to be conservative, not greedy. We don't want to capture multiple fields within one set of quotes.

Array: The string array is useful if you want to copy the fields to a new array. This way, we turn the groups into an array, similar to how Split works.

Split

Finally: The fields we captured are displayed to the console. You can see there are 5 output fields. This is our required result.

C# program that parses quoted strings using System; using System.Text.RegularExpressions; class Program { static void Main() { // The input string string line = "INSERT INTO country VALUES ('BH','BAHRAIN','Bahrain','BHR','048');"; // Match all quoted fields MatchCollection col = Regex.Matches(line, @"'(.*?)'"); // 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) } // Display the fields foreach (string field in fields) { Console.WriteLine(field); } } } Output 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.
Summary. We extracted quoted values from an input string using Regex.Matches. This style of code is useful to every developer working with regular expressions extensively, and is useful for your tool chain.Regex
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls