C#で複数の文字列を正規表現を使って一致させる方法は何ですか。
C#では、Regexクラスを使用して複数の文字列をマッチングすることができます。以下に示すのは例のコードです。
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string input = "Hello world! This is a test.";
string[] keywords = { "Hello", "world", "test" };
foreach (string keyword in keywords)
{
// 使用Regex类的静态方法Match来进行匹配
Match match = Regex.Match(input, keyword);
if (match.Success)
{
Console.WriteLine("Found '{0}' at position {1}.", keyword, match.Index);
}
else
{
Console.WriteLine("'{0}' not found.", keyword);
}
}
}
}
結果は以下の通りです:
Found 'Hello' at position 0.
Found 'world' at position 6.
Found 'test' at position 21.
上記の例では、私たちは文字列配列keywordsを定義し、ループを使用してRegex.Matchメソッドを使用して入力文字列input内でキーワードを1つずつ一致させます。 一致する項目が見つかった場合、キーワードの位置を出力します。 それ以外の場合、not foundを出力します。