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

时间:2010-06-25 09:59:07

标签: c# .net regex lookaround capture-group

我的格式为[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 ]

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

真正让我烦恼的是,我不能使用(.*?)来捕捉字符串,因为看起来非贪婪不适用于外观。

我也尝试过:Regex.Split(str, @"\]\.\[").Last().TrimEnd(']');,但我对这个解决方案并不感兴趣

4 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:2)

假设您可以保证输入格式,并且它只是您想要的最后一个条目,可以使用LastIndexOf

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

int lastBracket = input.LastIndexOf("[");
string result = input.Substring(lastBracket + 1, input.Length - lastBracket - 2);

答案 2 :(得分:0)

使用String.Split():

string input = "[abc].[some other string].[can.also.contain.periods].[our match]";
char[] seps = {'[',']','\\'};
string[] splitted = input.Split(seps,StringSplitOptions.RemoveEmptyEntries);

你在splitted [7]中获得“out match”并且can.also.contain.periods保留为一个字符串(splitted [4])

编辑:数组将在[]中包含字符串然后。等等,所以如果你有一个可变数量的组,你可以使用它来获得你想要的值(或删除只是'。'的字符串)

编辑将反斜杠添加到分隔符以处理'\ [abc \]'

等案例

Edit2:用于嵌套[]:

string input = @"[abc].[some other string].[can.also.contain.periods].[our [the] match]";
string[] seps2 = { "].["};
string[] splitted = input.Split(seps2, StringSplitOptions.RemoveEmptyEntries);

你们在最后一个元素(索引3)中的[匹配],你必须删除额外的元素]

答案 3 :(得分:0)

您有几种选择:

  • RegexOptions.RightToLeft - 是的,.NET正则表达式可以做到这一点!使用它!
  • 将整个事物与贪婪前缀匹配,使用括号来捕获您感兴趣的后缀
    • 通常,pattern变为.*(pattern)
    • 在这种情况下,.*\[([^\]]*)\],然后提取\1抓取的内容(see this on rubular.com

参考