PowerShell: Regex Examples

# Example 1 Simple 10-digit match
$x='123-456-7890'
[regex]$regex10Digits='\({0,1}\d{0,1}\){0,1}\-{0,1}(\d{3})'
$areaCode=$regex10Digits.Match($x).Groups[1].Value

# Example 2 IP Version 4 Addresses
$defaultInterface=get-wmiobject win32_networkadapterconfiguration -filter "ipenabled='true'"|?{$_.DefaultIpGateway -ne $null}
$regexIpv4 = "\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"
$ipv4=$defaultInterface.IpAddress|?{$_ -match $regexIpv4}

# Example 3 Social Security Number
$regexSsn='^(?!\b(\d)\1+-(\d)\1+(-){0,1}(\d)\1+\b)(?!123-45-6789|219-09-9999|078-05-1120|457-55-5462)(?!666|000|9\d{2})\d{3}(-){0,1}(?!00)\d{2}(-){0,1}(?!0{4})\d{4}$'
'123456789' -match $regexSsn

Leave a Reply

Your email address will not be published. Required fields are marked *