C# 使用正则表达式返回数组/列表

C# 使用正则表达式返回数组/列表,c#,.net,regex,string,C#,.net,Regex,String,我想使用regex返回数组string[]或列表list 我想比较字符串,并返回所有以[开头和以]结尾的值 我是新来的regex,请您解释一下生成正确结果所使用的语法。Stallman说:“当您想使用regexp解决问题时,现在有两个问题。” 在您的情况下,它类似于^\[.\]$ string模式=Regex.Escape(“[”+”(.*)”); string input=“Test[Test2]…示例文本[Test3]”; MatchCollection matches=Regex.mat

我想使用
regex
返回数组
string[]
或列表
list

我想比较
字符串
,并返回所有以
[
开头和以
]
结尾的值

我是新来的
regex
,请您解释一下生成正确结果所使用的语法。

Stallman说:“当您想使用regexp解决问题时,现在有两个问题。”

在您的情况下,它类似于^\[.\]$

string模式=Regex.Escape(“[”+”(.*)”);
string input=“Test[Test2]…示例文本[Test3]”;
MatchCollection matches=Regex.matches(输入,模式);
var myResultList=新列表();
foreach(匹配中的匹配)
{
myResultList.Add(match.Value);
}

结果列表将包含:[Test2],[Test3]

谢谢您的回答。假设我想将最后一个
]
更改为
?]
,我将如何操作,以便它返回
[Test2?]
?您的源字符串是否包含单词
'Test2?'
??对那么我将如何设置结尾字符呢?是的,您可以通过添加前面的
'\'
来转义它。
var result = Regex.Matches(input, @"\[([^\[\]]*)\]")
    .Cast<Match>()
    .Select(m => m.Groups[1].Value).ToArray();
var result = Regex.Matches(input, @"\[[^\[\]]*\]")
    .Cast<Match>()
    .Select(m => m.Value).ToArray();
string pattern = Regex.Escape("[") + "(.*?)]";
string input = "Test [Test2] .. sample text [Test3] ";

MatchCollection matches = Regex.Matches(input, pattern);
var myResultList = new List<string>();
foreach (Match match in matches)
{
    myResultList.Add(match.Value);
}