[英]Extracting column names from CREATE SQL command with Regular Expressions
我有這樣一個 sql 命令:
CREATE TABLE Tablex(
column1 INT,
column2 TEXT,
column3 INT,
column4 INT,
)
這個 CREATE 命令只是一個示例,列的名稱可以自由選擇。 如何在 c# 中通過 Regx 提取列名?
我的猜測是我們希望捕獲 column1 和其他類似的列,這個表達式可能會這樣做:
\s*(.+?)\s+[A-Z]+,
如果它總是以[AZ]+,
為界[AZ]+,
.
另一種選擇是在,
之后添加一個空格,
並在我們想要的列之前添加一個空格:
\s+(.+?)\s+[A-Z]+,?\s
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);
}
}
}
這是另一種選擇。 我不喜歡難以維護的復雜正則表達式:
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();
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.