简体   繁体   English

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

[英]Is there a function that returns index where RegEx match starts?

I have strings of 15 characters long. 我有15个字符长的字符串。 I am performing some pattern matching on it with a regular expression. 我正在使用正则表达式对其执行一些模式匹配。 I want to know the position of the substring where the IsMatch() function returns true. 我想知道IsMatch()函数返回true的子字符串的位置。

Question: Is there is any function that returns the index of the match? 问题:是否有任何函数返回匹配的索引?

For multiple matches you can use code similar to this: 对于多个匹配,您可以使用与此类似的代码:

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

Use Match instead of IsMatch: 使用Match而不是IsMatch:

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

Output: 输出:

Index of match: 2

Instead of using IsMatch, use the Matches method. 不使用IsMatch,而是使用Matches方法。 This will return a MatchCollection , which contains a number of Match objects. 这将返回MatchCollection ,其中包含许多Match对象。 These have a property Index . 这些都有房产指数

Regex.Match("abcd", "c").Index

2

Note# Should check the result of Match.success, because its return 0, and can confuse with Position 0, Please refer to Mark Byers Answer. 注意#应检查Match.success的结果,因为它返回0,并且可能与位置0混淆,请参考Mark Byers Answer。 Thanks. 谢谢。

Rather than use IsMatch() , use Matches : 而不是使用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"));

This will output a 4 这将输出4

a -1 indicates no match a -1表示不匹配

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM