提取[text1] [text2]标记之间的所有字符串

时间:2013-01-17 09:07:42

标签: c# asp.net regex

我有一个包含

的sql文本
"Select * from Table Where [PARAM1] = [PARAM2] ..."

我希望列出要列出的"[" "]"代码之间的列表。

我该怎么做?

7 个答案:

答案 0 :(得分:4)

您可以使用LINQ

来完成
string str = "Select * from Table Where [PARAM1] = [PARAM2] ...";
string[] Array = str.Split().Where(r=> r.StartsWith("[") && r.EndsWith("]"))
                    .Select(r=> r.Trim('[',']'))
                    .ToArray();

答案 1 :(得分:2)

您可以尝试使用正则表达式和一些LINQ:

Regex t = new Regex(@"\[([^]]*)\]");
List<String> parameters = t.Matches(input_string).Cast<Match>().Select(a => a.Groups[1].ToString()).ToList();

这将导致List包含两个匹配PARAM1PARAM2

答案 2 :(得分:2)

使用此代码段

string strRegex = @"\[(.*?)\]";
RegexOptions myRegexOptions = RegexOptions.IgnoreCase;
Regex myRegex = new Regex(strRegex, myRegexOptions);
string strTargetString = @"Select * from Table Where [PARAM1] = [PARAM2] ...";

foreach (Match myMatch in myRegex.Matches(strTargetString))
{
   // myMatch.Groups[0] - your string
}

答案 3 :(得分:1)

您也可以

List<string> matches=Regex.Matches(@"(?<=\[)[^\[\]]*(?=\])")
                          .Cast<Match>()
                          .Select(x=>x.Value)
                          .ToList();

答案 4 :(得分:1)

以下是您的需求:

Regex t = new Regex(@"\[(.*?)\]");

string str = @"Select * from Table Where [PARAM1] = [PARAM2] ...";

foreach (Match myMatch in myRegex.Matches(str))
{
   // myMatch.Groups[0] and so on....
}

Live Demo

答案 5 :(得分:0)

将MatchCollection转换为List use:

List<Match> myMatches = Regex.Matches("bla", @"\[[^]]*)\]").Cast<Match>.toList();

答案 6 :(得分:0)

您可以尝试使用此正则表达式:

Regex regex = new Regex(@"\[.*?\]");
var parameters = regex.Matches(sqlQueryString);
相关问题