我有 [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/