如何用带括号的单词替换字符串,但保留括号(s)?

时间:2017-11-28 23:45:01

标签: c# replace

我试图用句子周围的括号替换句子中的所有单词,但是用括号E.g保留单词的复数部分。 (s)...如果带有(s)的复数版本已经存在,请保留苹果。

 //TODO: Remove all parathesis from replaced words but keep (s) in there 
 //E.g. remove all parathesis from this sample but keep the (s) in there 
 //Mary ran to the (supermarket) to get her (grocerie(s)) but she forgot her (keys) and coin(s) 
//So supermarket,grocerie(s) and keys need the outer parenthesis removed so that it should be replaced with:
//Mary ran to the supermarket to get her grocerie(s) but she forgot her keys and coin(s) 

var keys = InformationScript.Split(' ');

string scriptWithoutParans = null;

foreach(var key in keys)
{
    if (!key.Equals("(s)"))
    {
        scriptWithoutParans = InformationScript.Replace("(", "").Replace(")", "");
    }
}

InformationScript = scriptWithoutParans;

上面的问题是,它似乎正在替换包括括号的所有内容,没有括号。除了(s)之外,我希望它能用于所有事情......怎么能这样做?

谢谢!

1 个答案:

答案 0 :(得分:2)

此解决方案将使用标记字符串替换function myFunction(){ //Object var x = document.getElementById("object"); var div = document.querySelectorAll(".col-lg-12 span"); for(var i = 0; i < div.length;i = i + 1){ div[i].innerHTML = x.value; } } 的所有实例,然后替换(s)(的所有实例,最后使用) <替换我们的标记字符串< / p>

(s)

结果:var token = "SAVED_TOKEN"; var InformationScript = "Mary ran to the (supermarket) to get her (grocerie(s)) but she forgot her (keys) and coin(s)"; //replace (s) with a token string that we can replace later var tokenized = Regex.Replace(InformationScript, "\\((s)\\)", token); //remove all remaining paranthesis, then replace our token with (s) InformationScript = Regex.Replace(tokenized, "\\(|\\)", "").Replace(token,"(s)");