2

我想搜索字符串的索引 \n\n 或 \n \n 或 \n \s* \n 搜索从某个索引开始,例如

 mystring.LastIndexof(regularexpression, mystartindex)

同样地

mystring.Indexof(regularexpression, mystartindex)
4

2 回答 2

2

使用这个Regex.Match重载

public Match Match(
    string input,
    int startat
)

例如

Regex re("\n\s*\n");
var index = re.Match(mystring, mystartindex).Index;

请注意,您可以使用它Match.NextMatch来获得下一场比赛:

Match m = Regex.Match(mystring, re);
while (m.Success) {
   Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
   m = m.NextMatch();
}

更新改编自您自己的解决方案:

public static class RegexMatchExtensions
{
    public static int LastIndexOf(this MatchCollection matches, int index)
    {
        var match = matches.Cast<Match>().LastOrDefault(m => m.Index <= index);
        return (match == null)? -1 : match.Index;
    }

    public static int IndexOf(this MatchCollection matches, int index)
    {
        var match = matches.Cast<Match>().FirstOrDefault(m => m.Index > index);
        return (match == null)? -1 : match.Index;
    }
}

用法:

/*private static readonly*/ Regex re = new Regex(@"\n\s*\n",
               RegexOptions.Compiled 
             | RegexOptions.Multiline
             | RegexOptions.CultureInvariant);

var doubleLineIndexes = re.Matches(wholeDocumentText);

var first = doubleLineIndexes.IndexOf(73);
var last = doubleLineIndexes.LastIndexOf(73);
于 2012-10-03T09:20:16.510 回答
0

正则表达式 re = new Regex(@"\n\s*\n"); MatchCollection DoubleLineIndexes = re.Matches(wholeDocumentText);

int LastIndexOf(MatchCollection mathes,int index) {

        for (int i = 0; i < mathes.Count; i++)
        {
            if (mathes[i].Index > index) return mathes[i-1].Index;
        }

        return -1;

    }

    int IndexOf(MatchCollection mathes, int index)
    {

        for (int i = 0; i < mathes.Count; i++)
        {
            if (mathes[i].Index > index) return mathes[i].Index;
        }

        return -1;

    }
于 2012-10-03T10:31:02.967 回答