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

标签 c# .net regex lookaround capture-group

我有 [abc].[一些其他字符串].[can.also.contain.periods].[我们的比赛]

形式的字符串

我现在想匹配字符串“our match”(即不带括号),所以我尝试了 lookarounds 之类的东西。我现在得到了正确的匹配,但我认为这不是一个干净的解决方案。

(?<=\.?\[)     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 ]

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

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

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

最佳答案

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

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]);

关于c# - 从c#中的字符串中提取最后一个匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3117087/

相关文章:

c# - 如何创建包含开放通用接口(interface)的 List<T> ?

c# - 在 C# 中命名一个类? MSDN推荐的名词?

.net - C# - 集合和泛型的备忘单

.net - 我可以在 .NET Windows 窗体中创建多列上下文菜单吗?

python - 如何在 Python 中的括号内添加字符?

Python 正则表达式从 url 中提取 vimeo id

javascript - 正则表达式:如何返回不在括号中的匹配项

c# - like 运算符给出零结果

c# - NET核心后台服务: "A task was canceled." Error

c# - 在 Windows 7 上使用 .NET 以编程方式创建/销毁网桥