Regular Expressions

Lets start with confession time. Regular expressions are something I have tended to avoid like the plague.  Why? I suppose its because I’ve never taken the time to understand them. Having seen some of the powerful things that can be done with them (and the fact that I’ve promised to talk about them at a UG meeting :-) ) its time to dig into them. They become incredibly useful with select-string and switch statements as we will see later.

From the conversations I’ve had there are a lot of people who feel the same way about regular expressions. Hopefully we can uncover some of the mystery.

We all seen or used something like this

PS> "Richard" -like "r*"
True

This is using a -like operator on a wildcard match. The PowerShell wildcards are * for zero or more characters, ? for a single character and [] to match a range or specified characters for example:

PS> "Richard" -like "[A-Z]*"
True

PS> "Richard" -like "R[ic][ic]*"
True

While not counted as regular expressions wildcard matches can be thought of as the lead in to regular expressions. The first difference is that we use -match instead of -like.

So to duplicate what we have seen so far we would use

PS> "Richard" -match "R."
True

PS> "Richard" -match "[A-Z]."
True

PS> "Richard" -match "[R][ic]+."
True

In the first example we are just replacing the * of the wildcard with the regular expression . which means any character except a new line. The second example has a match against a letter in the range A-Z and the third is looking for an "R" then either an i or a c twice (the + sign means one or more matches)

We have seen how regular expressions build on wildcard matching.  Next time we’ll dive a bit deeper in regular expressions.

 


Share this post :

 

About these ads
This entry was posted in Powershell. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s