C#正则表达式模式匹配关键字

问题描述 投票:-1回答:1

关于正则表达式的问题。我有一个字符串输入,我喜欢匹配我的字符串数组。输入不是常数。例如,我的测试输入是“test123MakeLunch23”和“testMakeLunch(1)”我有一个字符串数组。示例“MakeLunch”应该与我的测试输入匹配,“DeliverLunch”应该为false。我很难完成这项工作。

 string input = "test123MakeLunch23";
 List<string> lstKeywords = new List<string>() { "MakeLunch", "DeliverLunch"};
 foreach (var keyword in lstKeywords)
 {
   // this is not right
   string pattern = $@"^([a-zA-Z0-9{keyword}a-zA-Z0-9)$";

   // on MakeLunch should return true only
   bool ismatch = Regex.IsMatch(input,pattern,RegexOptions.IgnoreCase);
 }

你能为解决方案添加一些解释吗?谢谢。

regex c#-6.0
1个回答
0
投票

您只需要测试输入字符串中是否存在关键字。你不需要Regex:

string input = "test123MakeLunch23";
string keyword = "MakeLunch";
bool is_match = input.IndexOf(keyword) > -1;
© www.soinside.com 2019 - 2024. All rights reserved.