我想搜索字符串的索引\ n \ n或\ n \ n或\ n \ s * \ n搜索从某个索引开始,如
mystring.LastIndexof(regularexpression, mystartindex)
和类似的
mystring.Indexof(regularexpression, mystartindex)
答案 0 :(得分:2)
public Match Match(
string input,
int startat
)
E.g。
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);
答案 1 :(得分:0)
Regex 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;
}