Home
Map
Regex.Matches Quote ExampleUse the Regex.Matches method on quoted string data. Extract quoted string values.
C#
This page was last reviewed on Nov 17, 2023.
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.
Regex.Match
Regex Groups
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.
Regex.Matches
Part 1 The input string looks like an SQL query. We can see values are contained in parentheses and quotes.
Part 2 The MatchCollection is populated from the pattern specified. We use parentheses to indicate we want to capture values within quotes.
Part 3 The string array is useful if you want to copy the fields to a new array.
Array
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.
RegexOptions.Compiled
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 17, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.