C# Regex: Match Multiple Strings Explained
In C#, you can use the Regex class to match multiple strings. Here is an example code:
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);
}
}
}
}
The output will be:
Found 'Hello' at position 0.
Found 'world' at position 6.
Found 'test' at position 21.
In the example above, we defined a string array called keywords and used a loop along with the Regex.Match method to search for each keyword in the input string. If a match is found, it will output the position of the keyword; otherwise, it will output “not found”.