Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将包含字符串数组的变量放入正则表达式c#_C#_Arrays_Regex_Wpf - Fatal编程技术网

如何将包含字符串数组的变量放入正则表达式c#

如何将包含字符串数组的变量放入正则表达式c#,c#,arrays,regex,wpf,C#,Arrays,Regex,Wpf,我不熟悉使用正则表达式和搜索文本。 我想在一个文本中同时搜索多个单词,我正在考虑执行以下操作 string text = new TextRange(rtfMain.Document.ContentStart, rtfMain.Document.ContentEnd).Text; string[] searchWords = { "Danny", "Lucy", "Marco" }; Regex rx = new Regex( searchWords,

我不熟悉使用正则表达式和搜索文本。 我想在一个文本中同时搜索多个单词,我正在考虑执行以下操作

string text = new TextRange(rtfMain.Document.ContentStart, rtfMain.Document.ContentEnd).Text;

        string[] searchWords = { "Danny", "Lucy", "Marco" };
        Regex rx = new Regex( searchWords,
        RegexOptions.Compiled | RegexOptions.IgnoreCase);

MatchCollection matches = rx.Matches(text);

        foreach (Match match in matches)
        {
            ResultList.Add(match.ToString());
        } 
但regex似乎不接受

string[] searchWords 

我怎样才能使它工作,或者我的方法在实现我所需要的方面是错误的?

如果你需要匹配
Danny
Lucy
Marco
,你可以在术语之间放置一个管道(|),因为
Regex
构造函数只接受一个字符串作为模式

要从数组中生成单个(管道分隔)字符串,只需执行以下操作:

string[] searchWords = { "Danny", "Lucy", "Marco" };
string pattern = string.Join("|", searchWords);
Regex rx = new Regex( pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);

将搜索词合并成一个字符串,每个字符串之间用
|
分隔

string searchWords = "Danny|Lucy|Marco";
Regex rx = new Regex( searchWords,
RegexOptions.Compiled | RegexOptions.IgnoreCase);
如果需要数组,请动态地连接字符串

string[] searchWordsArray = { "Danny", "Lucy", "Marco" };

string searchWords = String.Join("|", searchWordsArray)
Regex rx = new Regex( searchWords,
RegexOptions.Compiled | RegexOptions.IgnoreCase);

在python中,我将用
“|”替换
searchWords
?如果你的答案是“因为有人告诉我它使正则表达式运行得更快”,那么你需要一个更好的理由。使用该选项会产生大量的管理费用,在大多数情况下,收益远远不足以抵消该成本。谢谢你的洞察力