15文字の文字列があります。正規表現を使用してパターンマッチングを実行しています。 IsMatch()
関数がtrueを返す部分文字列の位置を知りたい。
質問:一致のインデックスを返す関数はありますか?
複数の一致の場合、次のようなコードを使用できます。
Regex rx = new Regex("as");
foreach (Match match in rx.Matches("as as as as"))
{
int i = match.Index;
}
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
IsMatchを使用する代わりに、 Matches メソッドを使用します。これは MatchCollection を返します。これにはいくつかの Match オブジェクトが含まれています。これらには、プロパティ Index があります。
Regex.Match("abcd", "c").Index
2
Note#Match.successの結果を確認する必要があります。0を返すため、Position 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);
}