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.

>PS help about_regular*

I refer “Regular Expression Language Reference” MSDN article to understand more about regular expressions.  

In the below example, I wanted to extract Distinguished Name (DN) from a list of thousands of users from a text file.  Each line in that text file had a Unique DN.  So I resorted to Regular Expression to match DN in each line.   Check out the sample text which has DN in bolded text.

Some Random Text in which our DN is located so here is our Distinguished Name: CN=jsssmith2,OU=allUsers,OU=Payroll Users,DC=Com2,DC=myCompany,DC=com.  Everyline has this DN and we want to extract DN from every line.

I want to show how we can easily test this using powershell function we created. Copy the above text and paste in powershell using just right click.  Check out the syntax to test the function.


Our input string and regex are in double quotes above.  You can see the matching text in Yellow color.  The nice thing about this is if you get it wrong then iterating is easy because you just have to hit the up arrow on your keyboard and just change the regex part and it will give you another match.  

The matching regular expression was “CN.*DC=com”.  The neat thing in this approach I like is not remembering any software to open to test regexes.  Since I have PowerShell as my first item on my task bar I hit Win+1 and start testing.  I hope you like this approach.  If there is any easier approach or quicker way to test regular expressions then please let me know about it in the comments sections.

No comments:

Post a Comment