C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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.
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
It uses Regex.Matches. The MatchCollection is populated from the pattern specified. It uses parentheses in the pattern, which indicate the group we want to capture. Here, we indicate that 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.
It copies the groups to a new array. The string array we allocate next is not essential to this code but it 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.
Finally: The fields we captured are displayed to the console. You can see there are five output fields. This is our required result.
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.