Powershell Regular Expression Cheat Sheet



Regular expressions (regex) match and parse text. The regex language is a powerful shorthand for describing patterns. Powershell makes use of regular expressions in several ways. Sometimes it is easy to forget that these commands are using regex becuase it is so tightly integrated. You may already be using some of these commands and not even realize it.

  1. Powershell Regular Expression Find
  2. Powershell Regex Cheat Sheet Pdf
  3. Powershell Regular Expression Cheat Sheet

Image from xkcd.com, slightly altered

Powershell - Regular Expression - A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pat. A Regular Expression, or RegEx, is a sequence of special characters used to define a textual pattern match. RegEx processors are now included in numerous programming languages, including Java, JavaScript, PHP, Microsoft.NET, Perl, Python and VBScript. You'll be able to study them slowly, and to use them as a cheat sheet later, when you are reading the rest of the site or experimenting with your own regular expressions. If you overdose, make sure not to miss the next page, which comes back down to Earth and talks about some really cool stuff: The 1001 ways to use Regex.

  • Scope of this article
  • -match
  • -replace
  • -split
  • Switch
  • ValidatePattern
  • $Matches
  • .Net Regex
  • Multiple matches per line

Teaching the regex syntax and language is beyond the scope of this article. I will just cover what I need in order to focus on the PowerShell. My regex examples will intentionally be very basic.

Regex quick start

You can use normal numbers and characters in your patterns for exact matches. This works when you know exactly what needs to match. Sometimes you need a pattern where any digit or letter should make the match valid. Here are some basic patterns that I may use in these examples.

So a pattern of ddd-dd-dddd will match a USA social security number. Three digits, then a dash, two digits, then a dash and then 4 digits. Kindle accessibility plugin. There are better and more compact ways to represent that same pattern. But this will work for our examples today.

Regex resources

Here are some regular expression resources to help you find the right patterns for your task.

Interactive regex calculators:

Documentation and training:

This cmdlet is great for searching files or strings for a text pattern.

This example searches all the files in the $logFolder for lines that have the word Error. The pattern parameter is a regular expression and in this case, the word Error is valid regex. It will find any line that has the word error in it.

This one would search text documents for numbers that look like a USA Social Security Number.

The -match opperator takes a regular expression and returns $true if the pattern matches.

If you apply a match to an array, you will get a list of all the items that match the pattern.

Variations

-imatch makes it explicit that you are doing a case insensitive operation (the default)

-cmatch makes the operation case sensitive.

-notmatch returns true when there is no match.

The i and c variants of an operator is available for all comparison operators.

-like

The -like command is like -match except it does not use regex. It uses a simpler wildcard pattern where ? is any character and * is multiple unknown characters.

One important difference is that the -like command expects an exact match unless you include the wildcards. So if you are looking for a pattern within a larger string, you will need to add the wildcards on both ends. '*error*'

Sometimes all you need is a basic wildcard and that is where -like comes in. Jay bhim dj mix mp3 download.

This operator has -ilike, -clike, -notlike variants.

String.Contains()

If all you want to do is test to see if your string has a substring, you can use the string.contains($substring) appraoch.

string.contains() is case sensitive. This will perform faster then using the other opperators for this substring scenario.

The replace command uses regex for it’s pattern matching.

The other variants of this command are -creplace and -ireplace.

String.Replace()

The .Net String.Replace($pattern,$replacement) funciton does not use regex. I mention this because it performs faster than -replace.

This one is also case sensitive. Infact, all the string funtions are case sensitive.

Expression

This command is very often overlooked as one that uses a regex. We are often splitting on simple patterns that happen to be regex compatible that we never even notice.

Every once and a while, we will try to use some other character that means something else in regex. This will lead to very unexpected results. If we change our comma to a period, we get a bunch of blank lines.

The reason is that . will match any character, so in this case it matches every character. It ends up spliting at every character and giving us 9 empty values.

This is why it is important to remember what commands use regex.

-isplit and -csplit are the variants on this command.

String.Split()

Like with the replace command, there is a String.Split() function that does not use regex. It will be faster when splitting on a character (or substring) and give you the same results.

Regular

By default, the switch statement does exact matches. But it does have an -regex option to use regex matches instead.

This feature of switch is often overlooked.

Multiple switch matches

The interesting thing about using regex in a switch is that it will test each pattern so you can have several matches to one switch.

Run this example with the above switch statement:

Even though we had one string in the $message, 2 of the switch statements executed.

When creating an advanced function, you can add a [ValidatePattern()] to your parameter. This will validate the incomming value has the pattern that you expect.

This example requests a SSN from the user and it does the validation on the input. This will give the user an error message if not valid. My issue with this is that it does not give a good error message by default.

ValidateScript

One way around that is to use a [ValidateScript({..})] instead that throws a custom error message.

Now we get this error message

It may complicate our parameter, but it is much easier for our users to understand.

Validate ErrorMessage in PS 6

The use of a validate script just to give a good error message is kind of ugly. A new feature in PS 6 is that you can specify a custom error message for the ValiatePattern by using the ErrorMessage parameter. Here is how you would specify the ErrorMessage

When a value does not match, then the user is presented with the error below.

While this is a great new feature, it makes the code invalid for older versions of PowerShell. If I run that same code in Windows Powershell, I get this error message:

Validators on variables

Powershell Regular Expression Cheat Sheet

We mostly think of validators as part of an advanced function but the reality is that they apply to the variable and can be used outside of an advanced function.

I can’t say that I realy ever do this, but this would be a good trick to know. Aapke pyaar mein hum savarne lage mp3 song.

When you use the -match operator, an automatic variable called $matches contains the results of the match. If you have any sub expressions in your regex, those sub matches are also listed.

Named matches

This is one of my favorite features that most people don’t know about.If you use a named regex match, then you can access that match by name on the matches.

In the example above, the (?<Name>.+) is a named sub expression. This value is then placed in the $Matches.Name property. Same goes for SSN.

Because this is PowerShell, we have full access to the .net regex object. Most of them are covered by the functionality above. If you are getting into more advanced regex where you need custom options, then take a second look at this object.

All the .Net regex methods are case sensitive.

I’m going to touch on [regex]::Escape() because there is not a PowerShell equivalent.

Escape regex

regex is a complex language with common symbols and a shorthand syntax. There are times where you may want to match a literal value instead of a pattern. The [regex]::Escape() will escape out all the regex syntax for you.

Take this string for example (123)456-7890. It contains regex syntax that may not be obvious to you.

Expression

You may think this is matching a specific phone number but the thing it would match is 123456-7890. My point is that when you use a literal string where a regex is expected, that you will get unexpected results. This is where the [regex]::Escape() solves that issue.

Powershell Regular Expression Find

I don’t want to talk on this too much because this is an anti-pattern. If you are needing to regex escape your entire pattern before you match it, then you should use the String.Contains() method instead.

The only time you should be escaping a regex is if you are placing that value inside a more complex regex. Even that is solved with a more complex regex pattern.

If you are using this in your code. Rethink why you need it because odds are, you are using the wrong operator or method.

The -Match operator will only match once per line so the $matches variable only contains that first match. There are times where I want to grab every occurace of a pattern even if there are multiples per line. I have 2 ways that I approach this scenario.

-AllMatches

Select-String offers support for this with the -AllMatches parameter. In this case the returned object contains a Matches property for every match.

Regex Matches()

Powershell Regex Cheat Sheet Pdf

The [Regex] object method Matches is the other option.

When using Pester tests, the Should Match uses a regular expression.

When with Pester is the exception to the rule of not using [regex]::Escape(). Pester does not have a substring match alternative.

As you can see, there are a lot of places where you can use regex or may already using regex and not even know it. PowerShell did a good job of integrating these into the language. But be wary of using them if performance is a concern and you are not actually using regex pattern.

Powershell Regular Expression Cheat Sheet

Let me know if you discover any other common ways to use regex in PowerShell. I would love to hear about them and add them to my list.