Sunday, July 8, 2012

Using Powershell Function to Quickly Test Regular Expressions

I have found the easiest way to learn and experiment with regular expressions using Powershell.  In this function below, I have converted .Net code to test regular expressions into PowerShell Function test-regex.  It accepts two parameters $inputString and$regex.  In $regex you provide the regular expression you want to test. Put this little snippet into your PowerShell profile so that you don’t have to run this function everytime. PowerShell Profile will run this function everytime you open a new PowerShell session. This MSDN article explains on how to put functions into a PowerShell profile. function test-regex { param( [string]$inputString,
[string]$regex )$match = [System.Text.RegularExpressions.Regex]::Match($inputString,$regex)
Write-Host \$match.Value -foreground "Yellow"
}

This allows me to quickly test regular-expressions in powershell without much hassle. And if you want to find help about regular expressions inside powershell then you can type following command and get all help related to regular expressions.