Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 提取[text1][text2]标记之间的所有字符串_C#_Asp.net_Regex - Fatal编程技术网

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

C# 提取[text1][text2]标记之间的所有字符串,c#,asp.net,regex,C#,Asp.net,Regex,我有一个sql文本,其中包括 "Select * from Table Where [PARAM1] = [PARAM2] ..." 我想获取要列出的“[”“]”标记之间的列表 我该怎么做呢?您可以尝试使用正则表达式和一些LINQ: Regex t = new Regex(@"\[([^]]*)\]"); List<String> parameters = t.Matches(input_string).Cast<Match>().Select(a => a.Gr

我有一个sql文本,其中包括

"Select * from Table Where [PARAM1] = [PARAM2] ..."
我想获取要列出的
“[”“]”
标记之间的列表


我该怎么做呢?

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

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

这将产生一个列表,其中包含两个匹配项
PARAM1
PARAM2

,您可以使用LINQ执行此操作

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

要将MatchCollection转换为列表,请使用:

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

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

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

使用这个片段

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
}
你也可以

List<string> matches=Regex.Matches(@"(?<=\[)[^\[\]]*(?=\])")
                          .Cast<Match>()
                          .Select(x=>x.Value)
                          .ToList();
List matches=Regex.matches(@)(?以下是您需要的:

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....
}

是否还需要转义被求反部分上的内部']'?不,不需要。如果
^
后面的第一个字符是
]
,则它会自动转义(实际上这是表示“不包括
]
字符”的唯一方法)您是否尝试过子字符串,因为
+
是贪婪的,这不会返回第一个
[
和最后一个
]
之间的所有匹配项吗?