我正在尝试使用正则表达式 解析 SQL,以便返回别名(关键字AS
之后的字符串反击``)。例如输入
var test = "select t.`ProductID` AS `ProductID`, t.`AttributeID` AS `AttributeID`, t.`String_Value` AS `String_Value`, t.`Numeric_Value` AS `Numeric_Value`, t.`MetaData` AS `MetaData`, t.`DataType` AS `DataType`, t.`CreatedTime` AS `CreatedTime`, t.`CreatedBy` AS `CreatedBy`, t.`ModifiedTime` AS `ModifiedTime`, t.`ModifiedBy` from dfsfile.tmp1.my_json t";
预期回报是
"ProductID",
"AttributeID",
"String_Value",
"Numeric_Value",
"MetaData",
"DataType",
"CreatedTime",
"CreatedBy",
"ModifiedTime"
答案 0 :(得分:2)
像这样(正则表达式和 Linq ):
String test = "select t.`ProductID` AS `ProductID`, t.`AttributeID` ...";
// If you want to preserve `` the pattern is @"\bAS\s*(`[^`]*?`)"
String pattern = @"\bAS\s*`([^`]*?)`";
var result = Regex
.Matches(test, pattern, RegexOptions.IgnoreCase)
.OfType<Match>()
.Select(match => match.Groups[1].Value)
.ToArray(); // if you want, say, an array representation
Console.Write(String.Join(", ", result));
你会得到
ProductID, AttributeID, ... , ModifiedBy
但是,要小心:在一般情况下正则表达式不是用于解析SQL
的好选择;让我举一些例子来说明出现的问题:
-- commented AS ("abc" should not be returned)
select a /* AS `abc`*/
from tbl
-- commented value ("abc" should be returned, not "obsolete" or "proposed")
select a AS /*`obsolete`*/ `abc` /*`proposed`*/
from tbl
-- String ("abc" should not be returned)
select 'a AS `abc`'
from tbl
-- honest AS ("abc" should be returned)
select a /*'*/AS `abc`--'
from tbl
-- commented comment ("abc" should be returned)
select -- /*
a AS `abc`
--*/
from tbl