PowerShell RegEx

PowerShell has some very good regular expression facilities. I have never used regular expressions enough to retain a level of knowledge that allows me to just break out and write powerful ones unassisted. I keep a bookmark handy to regular-expressions.info whenever I need to produce more than just the basics.

The interactive nature of PowerShell is great in not only testing expressions for use within PowerShell but testing for other situations as well. The -match keyword is the PowerShell comparison operator that handles all the magic.

If you are testing simple string matches you can simply use:

PS> "The quick brown fox jumps over the lazy dog" -match "\b[Tt]he"

If you are testing a whole file you can use something like this:

Monday: Sunny
Tuesday: Cloudy
Wednesday: Clear and Cold
Thursday: Sunny
Friday: Partly Cloudy
Saturday: Windy
Sunday: Clear
PS> (Get-Content sample.txt) -match "\bSun"
Monday: Sunny
Thursday: Sunny
Sunday: Clear
PS> (Get-Content sample.txt) -match "^Sun"
Sunday: Clear

These are simple examples but you can see how easy it is to test regular expressions with PowerShell whether they are for use in your PowerShell work or not.


2 responses to “PowerShell RegEx

  1. …quick observation: if you want to search files for regex it’s *much* quicker (at least with larger files) to use select-string; this is designed for the job and takes regex patterns by default.


    • Good point Chris. This is good, I tend to think more in the logic between the paren’s (…) for If’s, and Switch’s, etc. But I also need to think more pipe-lining as well. I’ve been aware of Select-String but I should definitely keep that more in mind as I work through my PowerShell solutions. Thanks!


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 )

Facebook photo

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

Connecting to %s