今天我可以做硬代碼,但後來我想改變它,字符串字模式可以應用在@「\ bfood \ b」的一側。我想在不使用硬編碼的情況下將其變爲動態在動態方法中使用正則表達式
在futore中,我希望有「雞」而不是「食物」這個詞。
我試圖將代碼"@"\bfood\b"
替換爲@"\b" + pattern +"\b"
,但它不起作用。
string inputText = "food ddd dd";
string dddd = "\bfood\b";
string pattern = "food";
Regex rx = new Regex(@"\bfood\b", RegexOptions.None);
MatchCollection mc = rx.Matches(inputText);
if (rx.Match(pattern).Success)
{
int dd = 3;
}
我不會用'string.Format'在這裏,沒有'Regex.Escape'。也許'string.Format(@「\ b {0} \ b」,Regex.Escape(pattern))',除非應用程序允許用戶實際輸入正則表達式來搜索,這種情況很少見。 –
@AndersTornbladL我同意。我將我的推理與示例正則表達式聲明一起添加。 –