This seems to be a common question for C# users and after research and multiple attempts I cant for the life of me remove a pair of parenthesis from a string. The string I am having a problem with is Service (additional)
.
After doing my research I understand parenthesis are treated differently in Regex.Replace
. With my research also came multiple answers that I attempted but nothing seems to have worked. Here are some ways that I have tried to remove these parenthesis.
cleanValue = Regex.Replace(intVal, " ", "").Replace("(", "").Replace(")", "").Replace(",", "").Replace("/", "").Replace("-", "");
cleanValue = Regex.Replace(intVal, " ", "").Replace(@"\(", "").Replace(@"\)", "").Replace(",", "").Replace("/", "").Replace("-", "");
cleanValue = Regex.Replace(intVal, " ", "").Replace("[()]", "").Replace(",", "").Replace("/", "").Replace("-", "");
cleanValue = Regex.Replace(intVal, " ", "").Replace(@"[^a-zA-Z]", "").Replace(",", "").Replace("/", "").Replace("-", "");
None of these worked, after stepping through the code I just see the the space between the 'e' and '(' removed. Am I missing something?
In case anyone wanted to see the function
that is being used here it is:
public static string CleanExtra(string intVal)
{
string cleanValue;
if (intVal == null)
{
throw new System.ArgumentException("Value cannot be null", "original");
}
else
{
//cleanValue = Regex.Replace(intVal, " ", "").Replace("(", "").Replace(")", "").Replace(",", "").Replace("/", "").Replace("-", "");
//cleanValue = Regex.Replace(intVal, " ", "").Replace(@"\(", "").Replace(@"\)", "").Replace(",", "").Replace("/", "").Replace("-", "");
//cleanValue = Regex.Replace(intVal, " ", "").Replace("[()]", "").Replace(",", "").Replace("/", "").Replace("-", "");
cleanValue = Regex.Replace(intVal, " ", "").Replace(@"[^a-zA-Z]", "").Replace(",", "").Replace("/", "").Replace("-", "");
}
return cleanValue;
}
A Regex is overkill here as this can be done with a simple Replace
call:
string val = intVal.Replace("(", "").Replace(")", "");