C# 使用正则表达式替换单词

C# 使用正则表达式替换单词,c#,regex,C#,Regex,我有一句话里面可能有“不,或” 目前,我正在尝试测试并删除这些单词,但是,我不知道如何编写正确的正则表达式测试模式,有人能帮忙吗 我试过了 string test= ""; string str=" some words here "; if (str.ToLower().Contains(" not ")) { test = str.ToLower().Replace(" not ", " "); } else if (str.ToLower().Contains(" or ")

我有一句话里面可能有“不,或”

目前,我正在尝试测试并删除这些单词,但是,我不知道如何编写正确的正则表达式测试模式,有人能帮忙吗

我试过了

string test= ""; 
string str=" some words here ";

if (str.ToLower().Contains(" not ")) {
    test = str.ToLower().Replace(" not ", " "); 
} else if (str.ToLower().Contains(" or ")) { 
    test = str.ToLower().Replace(" or ", " ");
} 
你可以用它


我想你的意思是替换“不”和“或”


我试过string.replace(旧单词,新单词),效果不太好。你能告诉我们你试过什么吗?string test=“”;string str=“此处有一些单词”;if(str.ToLower().Contains(“not”){test=str.ToLower().Replace(“not”);}else if(str.ToLower().Contains(“或”){test=str.ToLower().Replace(“或“,”);}也许是一些输入的例子,以及你期望得到什么?根据你所说的,我认为string.replace是最好的解决方案。不知何故,string.replace不起作用。是的,我的意思是“not”和“or”都是一个单词,不是任何其他单词的一部分。你的部分起作用,但对于单词分数,它会在我测试时删除或从中删除。那么,你需要添加边界。尝试将其从(?:not | or)改为\b(?:not | or)\b。
string sString = "Sometimes not, or sometimes no";
string sNew = sString.Replace("not, or", String.Empty);
string resultString = null;
try {
    resultString = Regex.Replace(subjectString, "(?:not|or)", "", RegexOptions.Singleline | RegexOptions.IgnoreCase);
} catch (ArgumentException ex) {
    // Syntax error in the regular expression
}