【问题标题】:extract last match from string in c#从C#中的字符串中提取最后一个匹配项
【发布时间】:2010-06-25 09:59:06
【问题描述】:

我有[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#。如果有不涉及正则表达式的更简单的解决方案,我也很乐意知道

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

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

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      【解决方案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);
      

      【讨论】:

        【解决方案3】:

        使用 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);
        

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

        【讨论】:

        • 这可以在最后一个元素内使用转义括号吗?
        • @knittl:编辑了答案。如果您将反斜杠添加到分隔符,如果您的意思是 '\[abc\]',它将在同一索引处返回干净的值
        • 我的意思是[…].[…].[this is \[the\] last value],然后我想要"this is \[the\] last value"
        • @knittl:添加了代码 - 我用 '].[' 分割它,因为内括号没有 .现在拆分返回整个值。
        • 嗯,这基本上就是我的Regex.Split(…).Last().TrimEnd(']'); 所拥有的,但我认为我对 string.split 仍然存在一些误解
        【解决方案4】:

        您有多种选择:

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

        参考文献

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-05-29
          • 1970-01-01
          • 1970-01-01
          • 2018-10-27
          • 1970-01-01
          • 2014-08-15
          • 1970-01-01
          相关资源
          最近更新 更多