Search code examples
powershelltext-parsing

Trimming the end of string contains (#) - PowerShell


I'm having trouble trimming off some characters at the end of a string. The string usually looks like: (the number in the () is changing), I want to remove the () including the value inside, i added the Trim() and the end to remove spaces

$string = CollectorDCFService (1)
$string = LogicalShadowDatabase (3)

I tried to replace it with ""

$string.Replace("([0-9])"," ").Trim()
$string.Replace("(\*)"," ").Trim()

Its nor working...


Solution

    • The String.Replace() .NET method only supports literal (verbatim) string replacements, so you cannot use regex constructs such as [0-9] with it.

    • Use the regex-based -replace operator instead:

    • Formulate the regex in a way that makes a separate .Trim() call (to remove the spaces preceding (…)) unnecessary:

    $strings = 'CollectorDCFService (1)', 'LogicalShadowDatabase (3)'
    
    # -> 'CollectorDCFService', 'LogicalShadowDatabase'
    $strings -replace '\s+\([0-9]+\)$'
    

    For an explanation of the regex and the ability to experiment with it, see this regex101.com page.