C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Input:
('BH','BAHRAIN','Bahrain','BHR','048')
Fields:
BH
BAHRAIN
Bahrain
BHR
048
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.
SplitFinally: 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