Regex: Remove number in brackets at end of line in PowerShell

Viewed 80

When I run my code :

$SearchClass = "allreportstd"
$URI = "https://MySite/Default.aspx"

$WebRequest = Invoke-Webrequest -URI $URI -UseDefaultCredentials
$WebRequest.ParsedHtml.getElementsByClassName($SearchClass) | % {Write-Host $_.innerText} 

This produces the following output:

Workstations: Unsupported Win 10 editions (1803) (0)
Workstations: Unsupported Win 10 editions (1809 and earlier) (3)
Workstations: Unsupported Win 10 editions (1903) (7)
Workstations: Unsupported Win 2000 (0)
Workstations: Unsupported Win XP (1)
Workstations: Windows 10 editions (3775)

How to remove the last parentheses at the end of the line ?

  • Workstations: Windows 10 editions (3775) becomes Workstations: Windows 10 editions
  • Workstations: Unsupported Win 10 editions (1809 and earlier) (3) becomes Workstations: Unsupported Win 10 editions (1809 and earlier)

Thanks a lot for your help ..

1 Answers

You can use

$_.innerText -replace '\s*\([^()]*\)$'

The \s*\([^()]*\)$ regex matches zero or more whitespaces, then a (, then any zero or more chars other than ( and ) and then a ) at the end of string.

Note that it will not replace the (...) string that is followed with trailing whitespaces. To also consider those, you will need

$_.innerText -replace '\s*\([^()]*\)\s*$'

\s*$ matches zero or more whitespace chars at the end of string.

See the regex demo.

If you need to remove nested, balanced parentheses at the end of string, you can use

$_.innerText -replace '\s*\((?>[^()]+|(?<x>)\(|(?<-x>)\))*(?(x)(?!))\)\s*$'

See this regex demo. The (?>[^()]+|(?<x>)\(|(?<-x>)\))*(?(x)(?!)) part matches balanced round brackets.

Related