[工具]使用Expresso設計正規表示式
可以註冊取得免費版本使用
之前資料庫使用sqlite,想要開發將table shema匯出的功能
可是看到系統表格的資訊只有create table的sql指令
所以用這套工具將sql指令中有關
欄位名稱
欄位型態
欄位長度
的資訊擷取出來
以下是在Expresso的測試畫面
正規表示式
語意
測試文字
輸出的結果
執行view code
可以改變輸出的語言
可以產生程式碼,這裡我用C#
在程式中改寫引用如下
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace LibraryTest
{
class Program
{
static void Main(string[] args)
{
Regex MyRegex = new Regex(
".*\\[(?<ColumnName>.*)\\]\\s\\[(?<ColumnType>.*)\\]\\((?<Len" +
"gth>\\d{1,})\\).*",
RegexOptions.IgnoreCase
| RegexOptions.CultureInvariant
| RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled
);
string InputText = @"CREATE TABLE [Bank](
[Filter1] [char](1),
[UnitNo] [char](3) ,
[GroupNo] [char](4) ,
[Filter2] [char] (1),
[GroupName] [char](40) ,
[GroupNickName] [char](10) ,
[Address] [char](40) ,
[Filter3] [char] (1),
[PhoneSecNum] [char](3) ,
[PhoneNum] [char](8) ,
[Filter4] [char] (1),
[ValueDate] [char](6) ,
[ChangeType] [char](1) ,
[DefaultCode] [char](1) ,
[Remark] [char](2) ,
[Blank] [char](8)
)";
MatchCollection ms = MyRegex.Matches(InputText);
int count = 0;
List<SplitItems> items = new List<SplitItems>();
//將切割後的結果丟到輸出物件當中
foreach (Match temp in ms)
{
string searchresult = string.Empty;
foreach (Group grp in temp.Groups)
{
SplitItems tempitem = new SplitItems(MyRegex);
foreach (Capture cap in grp.Captures)
{
tempitem.SetValue(count, cap.Value);
count++;
}
items.Add(tempitem);
}
}
//顯示結果
foreach (SplitItems itemstore in items)
{
itemstore.DisplayValue();
}
Console.Read();
}
/// <summary>
/// 儲存正規表示式切割後的字串群組
/// </summary>
public class SplitItems
{
//格式
Dictionary<string, string> format = new Dictionary<string, string>();
//輸出結果
Dictionary<string, string> output = new Dictionary<string, string>();
private int matchcount;
public SplitItems() { }
public SplitItems(Regex MyRegex)
{
SetDictionary(MyRegex);
}
public void SetValue(int keyindex, string value)
{
int remainder = keyindex % matchcount;
foreach (KeyValuePair<string, string> tempvalue in format)
{
if (string.Compare(tempvalue.Value, remainder.ToString()) == 0)
{
output.Add(tempvalue.Key, value);
}
}
}
public void DisplayValue()
{
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<string, string> tempresult in output)
{
if (string.Compare(tempresult.Key, "0") != 0)
{
sb.Append(tempresult.Key + ":" + tempresult.Value + " ");
}
}
Console.WriteLine(sb.ToString());
}
public void SetDictionary(Regex MyRegex)
{
// Get the names of all the named and numbered capture groups
string[] GroupNames = MyRegex.GetGroupNames();
// Get the numbers of all the named and numbered capture groups
int[] GroupNumbers = MyRegex.GetGroupNumbers();
matchcount = GroupNames.Length;
for (int i = 0; i < GroupNames.Length; i++)
{
format.Add(GroupNames[i].ToString(), i.ToString());
}
}
}
}
}
輸出結果