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*"
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]*"
PS> "Richard" -like "R[ic][ic]*"
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."
PS> "Richard" -match "[A-Z]."
PS> "Richard" -match "[R][ic]+."
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 :|