如何使用带有起始索引和RegexOptions的Regex.Matches

时间:2019-06-11 03:11:13

标签: c# regex

使用Regex.Matches时,似乎没有办法同时指定RegexOptions和起始索引。

根据docs,有一种方法可以单独执行,但不能一起执行。

在下面的示例中,我希望matches仅包含字符串hEllo中的第二个text

string pattern = @"\bhello\b";
string text = "hello world. hEllo";
Regex r = new Regex(pattern);
MatchCollection matches;

// matches nothing
matches = r.Matches(text, 5)

// matches the first occurence
matches = Regex.Matches(text, pattern, RegexOptions.IgnoreCase)

有其他方法可以做到这一点吗?

1 个答案:

答案 0 :(得分:1)

我不相信你可以。您应该使用所需的选项实例化Regex

Regex r = new Regex(pattern, RegexOptions.IgnoreCase);

然后您可以简单地使用第一个示例中的现有代码,由于我们正在使用IgnoreCase选项,因此该示例现在应该匹配:

matches = r.Matches(text, 5);

Applicable constructor docs

Try it online