Search code examples
c#regexparentheses

C# remove parenthesis from string


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

Solution

  • After your call to Regex.Replace(...) you're actually using string.Replace(...). This makes your call to .Replace(@"[^a-zA-Z]", "") useless.

    Simplify it instead to:

    cleanValue = Regex.Replace(intVal, @"[^a-zA-Z]", "");
    

    This should remove all spaces and special characters which is what it looks like your code is trying to do. This includes parentheses.