我怎麼可以這樣寫:插入字符串中的正則表達式搜索C#
List<string> Words= new List<string>();
Regex re = new Regex(@"\b" + Words[n] + "\b");
我究竟問題是我如何使用正則表達式搜索從列表或字符串元素?
我怎麼可以這樣寫:插入字符串中的正則表達式搜索C#
List<string> Words= new List<string>();
Regex re = new Regex(@"\b" + Words[n] + "\b");
我究竟問題是我如何使用正則表達式搜索從列表或字符串元素?
可能的解決方案:
string testString = "cat and dog";
string[] Words = { "cat", "dog" };
foreach(string word in Words)
{
bool contains = Regex.IsMatch(testString, "\\b" + word + "\\b");
}
我會刪除局部變量'Regex re;'並調用靜態幫助器方法:'bool contains = Regex.IsMatch(testString,String.Format(「\ b {0} \ b」,word))' –
它應該是''\\ b「+ word +」\\ b「',你必須在正則表達式中使用雙反斜槓,因爲反斜槓是C#中的特殊字符 –
您可以使用所有的話在一個正則表達式:
var words= new List<string>();
var regex = new Regex(string.Format(@"\b(?:{0})\b", string.Join("|", words)), RegexOptions.Compiled);
這會給你的字符串正則表達式模式的列表:
List<string> words= new List<string>() { "cat", "dog" };
List<string> regexPatterns = words.Select(str => "\\b" + str + "\\b").ToList();
或者,如果你想要一個正則表達式對象列表:
List<Regex> regexObjects = words.Select(str => new Regex("\\b" + str + "\\b")).ToList();
你的意思是測試表達式中的每個條目'「\ b」單詞「\ b」' – Cjen1
我的意思是測試列表中的所有項目\ b \ b – rfk12
那麼你想要什麼:聲明'「\ b」+單詞「\ b」'會匹配任何重複的單詞。那麼你在檢查什麼?該代碼將用於檢查單詞是否包含在另一個字符串中? – Cjen1