字符串操作:如何拆分和连接带分隔符的字符串include

时间:2014-12-22 08:44:58

标签: c# asp.net regex vb.net string

我想拆分一个字符串并同时加入某个字符串。要拆分的字符串是SQL查询。 我设置拆分分隔符:{". ", ",", ", ", " "} 例如:

select id, name, age, status from tb_test where age > 20 and status = 'Active'

我希望它能产生如下结果:

select
id
,
name
,
age
,
status
from
tb_test
where
age > 20
and
status = 'Active'

但是我使用字符串拆分得到的只是逐字逐句。 我该怎么办才能让它有如上所述的结果?

提前致谢。

4 个答案:

答案 0 :(得分:2)

首先创建要拆分的所有SQL命令的列表:

List<string> sql = new List<string>() { 
     "select",
     "where",
     "and",
     "or",
     "from",
     ","
};

在该列表上循环并将该命令替换为$包围的自我。 此$美元符号将成为稍后拆分的字符。

string query = "select id, name, age, status from tb_test where age > 20 and status = 'Active'";

foreach (string s in sql)
{
     //Use ToLower() so that all strings don't have capital characters
     query = query.Replace(s.ToLower(), "$" + s.ToLower() + "$");
}

现在进行拆分并使用Trim()删除前端和后端的空格:

string[] splits = query.Split(new char[] { '$' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in splits) Console.WriteLine(s.Trim() + "\r\n");

这将拆分SQL命令。现在,您可以根据需要进一步定制它。

结果:

select
id
, 
name
, 
age
, 
status
from
tb_test
where
age > 20
and
status = 'Active'

答案 1 :(得分:2)

这是一个纯正的正则表达式解决方案:

(?:(?=,)|(?<![<>=]) +(?! *[<>=])|(?:(?<=,)))(?=(?:(?:[^'"]*(?P<s>['"])(?:(?!(?P=s)).)*(?P=s)))*[^'"]*$)

我做到了这样它可以处理通常的陷阱,比如字符串,但可能还有一些东西会打破它。请参阅demo


说明:

(?:
    (?=,) # split before a comma.
|
    (?<! # if not preceded by an operator, ...
        [<>=]
    )
     + #...split at a space...
    (?! *[<>=]) #...unless there's an operator behind the space.
|
    (?: # also split after a comma.
        (?<=,)
    )
)
# HOWEVER, make sure this isn't inside of a string.
(?= # assert that there's an even number of quotes left in the text.
    (?: # consume pairs of quotes.
        [^'"]* # all text up to a quote
        (?P<s>['"]) # capture the quote
        (?: # consume everything up to the next quote.
            (?!
                (?P=s)
            )
            .
        )*
        (?P=s)
    )*
    [^'"]* # then make sure there are no more quotes until the end of the text.
    $
)

答案 2 :(得分:1)

首先拆分拆分关键字SELECT,FROM,WHERE。 第二次拆分使用您的分隔符

拆分所有列

答案 3 :(得分:1)

使用正则表达式的一种方法:

string strRegex = @"(select)|(from)|(where)|([,\.])";
Regex myRegex = new Regex(strRegex, RegexOptions.IgnoreCase | RegexOptions.Multiline);
string strTargetString = @"select id, name, age, status from tb_test where age > 20 and     status = 'Active'";
string strReplace = "$1\r\n";

return myRegex.Replace(strTargetString, strReplace);  

这应输出:

  

选择
  id,
  名字,
  年龄,
  来自的状态   tb_test其中
  年龄> 20和status =&#39; Active&#39;

您可能希望在昏迷前执行另一个替换以修剪空格。 并且还使用&#34; \ r \ n $ 1 \ r \ n&#34;仅适用于sql关键字(select,from where,...)

希望得到这个帮助。