web-dev-qa-db-ja.com

RegExの一致が始まるインデックスを返す関数はありますか?

15文字の文字列があります。正規表現を使用してパターンマッチングを実行しています。 IsMatch()関数がtrueを返す部分文字列の位置を知りたい。

質問:一致のインデックスを返す関数はありますか?

30
Royson

複数の一致の場合、次のようなコードを使用できます。

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

IsMatchの代わりにMatchを使用します。

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

出力:

Index of match: 2
13
Mark Byers

IsMatchを使用する代わりに、 Matches メソッドを使用します。これは MatchCollection を返します。これにはいくつかの Match オブジェクトが含まれています。これらには、プロパティ Index があります。

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

2

Note#Match.successの結果を確認する必要があります。0を返すため、Position 0と混同される可能性があるため、Mark Byers Answerを参照してください。ありがとう。

4
YOU

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);
        }
2
Mitch Wheat