简体   繁体   中英

Extracting column names from CREATE SQL command with Regular Expressions

I have such a sql comman:

CREATE TABLE Tablex(
  column1 INT,
  column2 TEXT,
  column3 INT,
  column4 INT,
)

this CREATE command is only a sample, the name of columns can be freely selected. How can I extract column names via Regx in c#?

My guess is that we wish to capture column1 and other similar columns, which this expression might likely do so:

\s*(.+?)\s+[A-Z]+,

if it would be always bounded from right with [AZ]+, .

Demo 1

Other option would be to add an space after , and one before our desired columns:

\s+(.+?)\s+[A-Z]+,?\s

Demo 2

Test

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"\s*(.+?)\s+[A-Z]+,";
        string input = @"CREATE TABLE Tablex(
  column1 INT,
  column2 TEXT,
  column3 INT,
  column4 INT,
)
";
        RegexOptions options = RegexOptions.Multiline;

        foreach (Match m in Regex.Matches(input, pattern, options))
        {
            Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
        }
    }
}

Here is another option. I do not like complicated Regex that is hard to maintain :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication114
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = "CREATE TABLE Tablex(" +
                  " column1 INT," +
                  " column2 TEXT," +
                  " column3 INT," +
                  " column4 INT," +
               ")";

            string pattern1 = @"CREATE TABLE Tablex\((?'columns'[^)]+)\)";
            Match columnsMatch = Regex.Match(input, pattern1);
            string columns = columnsMatch.Groups["columns"].Value.Trim();
            string pattern = @"\s*(?'key'[^\s]+)\s+(?'value'\w+)[,$]";

            MatchCollection matches = Regex.Matches(columns, pattern);

            foreach(Match match in matches.Cast<Match>())
            {
                Console.WriteLine("Key : '{0}', Value : '{1}'", match.Groups["key"].Value, match.Groups["value"].Value);
            }
            Console.ReadLine();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM