spuder spuder - 5 months ago 24
PowerShell Question

Powershell regex to remove everything except key

Given a string like

'The fingerprint is: ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678910111'

How would you remove all text that isn't a 40 character string consisting of A-Z 0-9 ?

Currently I'm looking for the string 'The fingerprint is: ' and removing it, but I feel it would be safer to look for a 40 character alphanumeric.

$foo = $foo -replace 'The fingerprint is: ',''

I expect something like this to work, but no luck.

$foo = $foo -creplace '^[A-Z0-9]{40}',''

I've also tried just looking for the characters that match

$foo = $foo -match '[A-Z0-9]{40}'


Depends a bit, but if it's 40 contiguous and it's the only 40 character string you could use replace:

"The fingerprint is: ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678910111" -replace '.*([A-Z0-9]{40}).*', '$1'

Note: The replacement, $1, is a reference to the match group. It is not a PowerShell variable and is deliberately written in single quotes so it will not expand.