C# 是否有返回正则表达式匹配开始的索引的函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1851795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 21:23:31  来源:igfitidea点击:

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

c#regex

提问by Royson

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 IsMatch()function returns true.

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

Question:Is there is any function that returns the index of the match?

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

采纳答案by Adriaan Stander

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;
}

回答by spender

Instead of using IsMatch, use the Matchesmethod. This will return a MatchCollection, which contains a number of Matchobjects. These have a property Index.

使用Matches方法而不是使用 IsMatch 。这将返回一个MatchCollection,其中包含许多Match对象。这些有一个属性Index

回答by Mark Byers

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

回答by YOU

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.

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

回答by Paul Creasey

Console.Writeline("Random String".IndexOf("om"));

This will output a 4

这将输出一个 4

a -1 indicates no match

-1 表示不匹配

回答by Mitch Wheat

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);
        }