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

后端 未结 6 417
栀梦
栀梦 2020-12-29 02:10

I have strings of 15 characters long. I am performing some pattern matching on it with a regular expression. I want to know the position of the substring where the IsM

相关标签:
6条回答
  • 2020-12-29 02:45

    Use Match instead of 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
    
    0 讨论(0)
  • 2020-12-29 02:47

    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;
    }
    
    0 讨论(0)
  • 2020-12-29 02:47
    Console.Writeline("Random String".IndexOf("om"));
    

    This will output a 4

    a -1 indicates no match

    0 讨论(0)
  • 2020-12-29 02:52
    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. Thanks.

    0 讨论(0)
  • 2020-12-29 02:55

    Instead of using IsMatch, use the Matches method. This will return a MatchCollection, which contains a number of Match objects. These have a property Index.

    0 讨论(0)
  • 2020-12-29 03:03

    Rather than use IsMatch(), use 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);
            }
    
    0 讨论(0)
提交回复
热议问题