C# Regex.Matches: Quote

Regex type

Strings sometimes have quoted values. It is often useful to extract these values. This is useful for parsing 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 a regular expression in the C# language.

This C# example uses the Regex.Matches method on quoted string data.

Input

('BH','BAHRAIN','Bahrain','BHR','048')

Fields

BH
BAHRAIN
Bahrain
BHR
048

Example

Here we see there is an easy way to match values within single quotes or double quotes using Regex.Matches. To use Regex.Matches, you pass it a pattern, which must specify the group you are capturing. Our group here is surrounded by single quote characters.

Program that parses quoted strings [C#]

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
Note

Description. The first part of the example is the input string declaration. The string contains several quotes values, which are the fields we need to extract.

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. The question mark means to be conservative, not greedy. We don't want to capture multiple fields within one set of quotes.

Regex.Matches Method

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, which is what our required result is.

Split String Examples

Performance

Performance optimization

Here we mention that regular expressions in C# do not result in optimal execution time. Therefore, in performance-critical situations, you will want a more complex parser. Often when dealing with text data, developers are importing data, which doesn't require heavy performance tuning.

Summary

Here we saw how you can extract 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 Type
.NET