从 C# 中的字符串中提取最后一个匹配项

kni*_*ttl 3 .net c# regex capture-group lookaround

我有表格中的字符串 [abc].[some other string].[can.also.contain.periods].[our match]

我现在想匹配字符串“我们的匹配”(即没有括号),所以我玩了环视和诸如此类的东西。我现在得到了正确的匹配,但我认为这不是一个干净的解决方案。

(?<=\.?\[)     starts with '[' or '.['
([^\[]*)      our match, i couldn't find a way to not use a negated character group
              `.*?` non-greedy did not work as expected with lookarounds,
              it would still match from the first match
              (matches might contain escaped brackets)
(?=\]$)       string ends with an ]
Run Code Online (Sandbox Code Playgroud)

语言是.net/c#。如果有不涉及正则表达式的更简单的解决方案,我也很高兴知道

真正让我恼火的是,我不能(.*?)用来捕获字符串,因为它似乎非贪婪不适用于lookbehinds。

我也试过:Regex.Split(str, @"\]\.\[").Last().TrimEnd(']');,但我也不是很喜欢这个解决方案

Jac*_*rdt 5

以下应该可以解决问题。假设字符串在最后一次匹配后结束。

string input = "[abc].[some other string].[can.also.contain.periods].[our match]";

var search = new Regex("\\.\\[(.*?)\\]$", RegexOptions.RightToLeft);

string ourMatch = search.Match(input).Groups[1]);
Run Code Online (Sandbox Code Playgroud)