Reputation: 36712
I need to search for the amount of backslashes in a string to determine some file path parameters. I have not worked out a way to seach for a backslash without Powershell thinking it is an escapee character.
([regex]::Matches($FilePath, "\" )).count
Or
$a -match "\"
These both come up with an error "Illegal \ at end of pattern"
Thanks!
Upvotes: 3
Views: 9462
Reputation: 71
Backslash is an escape character in regex.
Heres's how I did it:
$backslashCount = $FilePath | Select-String -Pattern "\\" -AllMatches
$backslashCount.Matches.Length
Select-String documentation:
Select-String (Microsoft.PowerShell.Utility) - PowerShell | Microsoft Learn
Upvotes: 0
Reputation: 7029
You can escape a backslash with a backslash:
[Regex]::Matches($FilePath, "\\").Count
Upvotes: 5