是否有一个函数返回RegEx匹配开始的索引?

我有15个字符长的字符串。 我正在使用正则表达式对其执行一些模式匹配。 我想知道IsMatch()函数返回true的子字符串的位置。

问题:是否有任何函数返回匹配的索引?

对于多个匹配,您可以使用与此类似的代码:

 Regex rx = new Regex("as"); foreach (Match match in rx.Matches("as as as as")) { int i = match.Index; } 

不使用IsMatch,而是使用Matches方法。 这将返回MatchCollection ,其中包含许多Match对象。 这些都有房产指数 。

使用Match而不是IsMatch:

  Match match = Regex.Match("abcde", "c"); if (match.Success) { int index = match.Index; Console.WriteLine("Index of match: " + index); } 

输出:

 Index of match: 2 
 Regex.Match("abcd", "c").Index 2 

注意#应检查Match.success的结果,因为它返回0,并且可能与位置0混淆,请参考Mark Byers Answer。 谢谢。

而不是使用IsMatch() ,使用Matches

  const string stringToTest = "abcedfghijklghmnopqghrstuvwxyz"; const string patternToMatch = "gh*"; Regex regex = new Regex(patternToMatch, RegexOptions.Compiled); MatchCollection matches = regex.Matches(stringToTest); foreach (Match match in matches ) { Console.WriteLine(match.Index); } 
 Console.Writeline("Random String".IndexOf("om")); 

这将输出4

a -1表示不匹配