Euridice01
Euridice01

Reputation: 2568

How can I do a string replacement for words with parenthesis but keep the parenthesis with (s)?

I'm trying to do a string replacement for all words in the sentence with parenthesis around the word but keep the pluralized part of the word with the parenthesis E.g. (s)... like keep apple(s) if the pluralized version of the word with (s) is already there.

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

The issue with the above is, it appears to be replacing everything including the (s) parenthesis with no parenthesis. I want it to be for everything except for (s)... How can do that?

Thanks!

Upvotes: 0

Views: 81

Answers (1)

Zeb Rawnsley
Zeb Rawnsley

Reputation: 2220

This solution will replace all instances of (s) with a token string, then replace all instances of ( or ), and finally replace our token string with (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)");

Result: Mary ran to the supermarket to get her grocerie(s) but she forgot her keys and coin(s)

Upvotes: 2

Related Questions