【问题标题】:how do i get the position in the original string where the last character of the captured substring found我如何获得在原始字符串中找到捕获的子字符串的最后一个字符的位置
【发布时间】:2015-11-05 23:35:45
【问题描述】:

伙计们,这是我的原始字符串, '010000111'

我需要找到这个模式'10000111'。所以我使用下面的正则表达式来做到这一点。

匹配 m = Regex.Match("010000111", @"[1][0][0][0][0][1]+");

我从这个正则表达式中得到了正确的答案。但问题是我需要在原始字符串中获取捕获字符串的最后一个字符的位置,这意味着根据我的示例我捕获的模式是 '10000111' 根据捕获的模式,我的最后一个索引是 7,但是当它与原始字符串比较时,它是 8。

我使用了 lastIndexOf('1') 函数。但它给出了捕获字符串的索引。

你能帮我解决这个问题吗?

【问题讨论】:

    标签: c# asp.net regex


    【解决方案1】:

    您不需要正则表达式来执行此操作。

    要检查字符串是否包含另一个,请使用someString.IndexOf("someOtherString") 方法。这将为您提供序列中第一个字符的索引。

    要得到最后一个字符的位置,你所要做的就是将被测字符串的长度相加并减去1:

    var firstString = "010000111";
    var secondString = "10000111";
    
    var positionOfSecondOverFirst = firstString.IndexOf(secondString); // 1
    
    var firstContainsSecond = (positionOfSecondOverFirst >= 0); // true
    
    var positionOfLastChar = positionOfSecondOverFirst + secondString.Length - 1; // 8
    

    参考:https://msdn.microsoft.com/library/k8b1470s(v=vs.110).aspx

    【讨论】:

    • 非常感谢您的回答
    【解决方案2】:

    您想使用正则表达式的任何特殊原因?我认为您想要完成的工作只需使用IndexOf

    public static int GetIndex()
    {
        const string input = "010000111";
        const string substring = "10000111";
    
        var startIndex = input.IndexOf(substring);
        if (startIndex != -1)
        {
            return startIndex + substring.Length;
        }
    
        return -1;
    }
    

    【讨论】:

      【解决方案3】:

      您可以使用以下方法:

      private int findLastIndex(string s1, string s2)
      {
        if (s1.indexOf(s2)>-1)
        {
          return s1.indexOf(s2) + s2.Length - 1;
        }
        else
          return -1; //not found
      }
      

      【讨论】:

      • 非常感谢您的回答
      • 很高兴为您提供帮助。如果您选择我的答案作为正确答案,如果您在代码中使用了我的回复,我将不胜感激。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-10
      • 2011-08-22
      • 2013-11-25
      • 2015-12-26
      • 2011-07-07
      • 2011-08-17
      相关资源
      最近更新 更多