如何使用c#在单个字符串中对多个项目进行正则表达式?

Sam*_*r83 1 c# regex

我的字符串是以下格式:

"[Item1],[Item2],[Item3],..."
Run Code Online (Sandbox Code Playgroud)

我希望能够获得item1,item2,item3等.

我正在尝试以下grep表达式:

MatchCollection matches = Regex.Matches(query, @"\[(.*)\]?");
Run Code Online (Sandbox Code Playgroud)

但是,不是匹配每个项目,而是得到 "item1][item2][..."

我做错了什么?

p.s*_*w.g 5

你需要使用非贪婪的量词,如下所示:

MatchCollection matches = Regex.Matches(query, @"\[(.*?)\]?");
Run Code Online (Sandbox Code Playgroud)

或者是一个排除字符的字符类],如下所示:

MatchCollection matches = Regex.Matches(query, @"\[([^\]]*)\]?");
Run Code Online (Sandbox Code Playgroud)

然后,您可以像这样访问您的匹配:

matches[0].Groups[1].Value // Item1
matches[1].Groups[1].Value // Item2
matches[2].Groups[1].Value // Item3
Run Code Online (Sandbox Code Playgroud)