在正则表达式搜索中插入字符串C#

时间:2022-09-13 07:48:09

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?

我的问题是如何使用正则表达式从列表或字符串中搜索元素?

3 个解决方案

#1


1  

Possible Solution:

可能解决方案

string testString = "cat and dog";
string[] Words = { "cat", "dog" };

foreach(string word in Words)
{
    bool contains = Regex.IsMatch(testString, "\\b" + word + "\\b");
}

#2


0  

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);

#3


0  

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();

#1


1  

Possible Solution:

可能解决方案

string testString = "cat and dog";
string[] Words = { "cat", "dog" };

foreach(string word in Words)
{
    bool contains = Regex.IsMatch(testString, "\\b" + word + "\\b");
}

#2


0  

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);

#3


0  

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();