[英]Insert string in regex search C#
How I can write this:我怎么能写这个:
List<string> Words= new List<string>();
Regex re = new Regex(@"\b" + Words[n] + "\b");
My exactly question is how I can search elements from list or string using regex?我的确切问题是如何使用正则表达式从列表或字符串中搜索元素?
Possible Solution:可能的解决方案:
string testString = "cat and dog";
string[] Words = { "cat", "dog" };
foreach(string word in Words)
{
bool contains = Regex.IsMatch(testString, "\\b" + word + "\\b");
}
You can use all words in one regex:您可以在一个正则表达式中使用所有单词:
var words= new List<string>();
var regex = new Regex(string.Format(@"\b(?:{0})\b", string.Join("|", words)), RegexOptions.Compiled);
This will give you a list of string regex patterns:这将为您提供字符串正则表达式模式列表:
List<string> words= new List<string>() { "cat", "dog" };
List<string> regexPatterns = words.Select(str => "\\b" + str + "\\b").ToList();
Or if you want a list of Regex objects:或者,如果您想要一个 Regex 对象列表:
List<Regex> regexObjects = words.Select(str => new Regex("\\b" + str + "\\b")).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.