A recorded presentation of Tome Tanasovski's regex talk for the UK PowerShell UserGroup PowerShellAdmin.com's extensive PowerShell Regex Article by Joakim Svendsen Regular Expression Resources. Expresso Regular Expression Tool Real-time Regex testing Cheat sheet and slide deck for Tome's regular expression presentation Regex cheat sheet. To match larger numbers requires a more complex regex, to test the numbers 0 to 19 test a match with 0-9 OR ( ) the number 1 followed by 0-9: PS C: 12 -match '^(0-9 10-9)$' True. To test the numbers 0 to 99: PS C: 45 -match '^(0-9 0-90-9)$' True. Will match a single character: PS C: 'cat' -match 'c.t' True. With the regex cheat sheet above, you can dissect and verify what each token within a regex expression actually does.However, you may still be a little confused as to how to put these tokens together to create an expression for a particular purpose. Match,-notmatch Regular expression match-like,-notlike Wildcard matching-contains,-notcontains Check if value in array. PowerShell is a task based command line shell and scripting language. To run it, click Start, type PowerShell, run PowerShell ISE. PowerShell Basic Cheat Sheet. Title: Repository.
- Powershell Regular Expression Cheat Sheet Answers
- Regex Cheat Sheet Pdf
- Regular Expression Powershell
- Powershell Regular Expression Match Digit
- Regex Cheat Sheet
- Powershell Regular Expression Cheat Sheet Example
A regular expression is a pattern that the regular expression engine attempts to match in input text. A pattern consists of one or more character literals, operators, or constructs. For a brief introduction, see .NET Regular Expressions.
Each section in this quick reference lists a particular category of characters, operators, and constructs that you can use to define regular expressions.
We've also provided this information in two formats that you can download and print for easy reference:
Character Escapes
The backslash character () in a regular expression indicates that the character that follows it either is a special character (as shown in the following table), or should be interpreted literally. For more information, see Character Escapes.
| Escaped character | Description | Pattern | Matches |
|---|---|---|---|
a | Matches a bell character, u0007. | a | 'u0007' in 'Error!' + 'u0007' |
b | In a character class, matches a backspace, u0008. | [b]{3,} | 'bbbb' in 'bbbb' |
t | Matches a tab, u0009. | (w+)t | 'item1t', 'item2t' in 'item1titem2t' |
r | Matches a carriage return, u000D. (r is not equivalent to the newline character, n.) | rn(w+) | 'rnThese' in 'rnThese arentwo lines.' |
v | Matches a vertical tab, u000B. | [v]{2,} | 'vvv' in 'vvv' |
f | Matches a form feed, u000C. | [f]{2,} | 'fff' in 'fff' |
n | Matches a new line, u000A. | rn(w+) | 'rnThese' in 'rnThese arentwo lines.' |
e | Matches an escape, u001B. | e | 'x001B' in 'x001B' |
nnn | Uses octal representation to specify a character (nnn consists of two or three digits). | w040w | 'a b', 'c d' in 'a bc d' |
xnn | Uses hexadecimal representation to specify a character (nn consists of exactly two digits). | wx20w | 'a b', 'c d' in 'a bc d' |
cXcx | Matches the ASCII control character that is specified by X or x, where X or x is the letter of the control character. | cC | 'x0003' in 'x0003' (Ctrl-C) |
unnnn | Matches a Unicode character by using hexadecimal representation (exactly four digits, as represented by nnnn). | wu0020w | 'a b', 'c d' in 'a bc d' |
| When followed by a character that is not recognized as an escaped character in this and other tables in this topic, matches that character. For example, * is the same as x2A, and . is the same as x2E. This allows the regular expression engine to disambiguate language elements (such as * or ?) and character literals (represented by * or ?). | d+[+-x*]d+ | '2+2' and '3*9' in '(2+2) * 3*9' |
Character Classes
A character class matches any one of a set of characters. Character classes include the language elements listed in the following table. For more information, see Character Classes.
| Character class | Description | Pattern | Matches |
|---|---|---|---|
[character_group] | Matches any single character in character_group. By default, the match is case-sensitive. | [ae] | 'a' in 'gray''a', 'e' in 'lane' |
[^character_group] | Negation: Matches any single character that is not in character_group. By default, characters in character_group are case-sensitive. | [^aei] | 'r', 'g', 'n' in 'reign' |
[first-last] | Character range: Matches any single character in the range from first to last. | [A-Z] | 'A', 'B' in 'AB123' |
. | Wildcard: Matches any single character except n. To match a literal period character (. or u002E), you must precede it with the escape character (.). | a.e | 'ave' in 'nave''ate' in 'water' |
p{name} | Matches any single character in the Unicode general category or named block specified by name. | p{Lu}p{IsCyrillic} | 'C', 'L' in 'City Lights''Д', 'Ж' in 'ДЖem' |
P{name} | Matches any single character that is not in the Unicode general category or named block specified by name. | P{Lu}P{IsCyrillic} | 'i', 't', 'y' in 'City''e', 'm' in 'ДЖem' |
w | Matches any word character. | w | 'I', 'D', 'A', '1', '3' in 'ID A1.3' |
W | Matches any non-word character. | W | ' ', '.' in 'ID A1.3' |
s | Matches any white-space character. | ws | 'D ' in 'ID A1.3' |
S | Matches any non-white-space character. | sS | ' _' in 'int __ctr' |
d | Matches any decimal digit. | d | '4' in '4 = IV' |
D | Matches any character other than a decimal digit. | D | ' ', '=', ' ', 'I', 'V' in '4 = IV' |
Anchors
Anchors, or atomic zero-width assertions, cause a match to succeed or fail depending on the current position in the string, but they do not cause the engine to advance through the string or consume characters. The metacharacters listed in the following table are anchors. For more information, see Anchors.
| Assertion | Description | Pattern | Matches |
|---|---|---|---|
^ | By default, the match must start at the beginning of the string; in multiline mode, it must start at the beginning of the line. | ^d{3} | '901' in '901-333-' |
$ | By default, the match must occur at the end of the string or before n at the end of the string; in multiline mode, it must occur before the end of the line or before n at the end of the line. | -d{3}$ | '-333' in '-901-333' |
A | The match must occur at the start of the string. | Ad{3} | '901' in '901-333-' |
Z | The match must occur at the end of the string or before n at the end of the string. | -d{3}Z | '-333' in '-901-333' |
z | The match must occur at the end of the string. | -d{3}z | '-333' in '-901-333' |
G | The match must occur at the point where the previous match ended. | G(d) | '(1)', '(3)', '(5)' in '(1)(3)(5)[7](9)' |
b | The match must occur on a boundary between a w (alphanumeric) and a W (nonalphanumeric) character. | bw+sw+b | 'them theme', 'them them' in 'them theme them them' |
B | The match must not occur on a b boundary. | Bendw*b | 'ends', 'ender' in 'end sends endure lender' |
Grouping Constructs
Grouping constructs delineate subexpressions of a regular expression and typically capture substrings of an input string. Grouping constructs include the language elements listed in the following table. For more information, see Grouping Constructs.
| Grouping construct | Description | Pattern | Matches |
|---|---|---|---|
(subexpression) | Captures the matched subexpression and assigns it a one-based ordinal number. | (w)1 | 'ee' in 'deep' |
(?<name>subexpression)or (?'name'subexpression) | Captures the matched subexpression into a named group. | (?<double>w)k<double> | 'ee' in 'deep' |
(?<name1-name2>subexpression)or (?'name1-name2'subexpression) | Defines a balancing group definition. For more information, see the 'Balancing Group Definition' section in Grouping Constructs. | (((?'Open'()[^()]*)+((?'Close-Open'))[^()]*)+)*(?(Open)(?!))$ | '((1-3)*(3-1))' in '3+2^((1-3)*(3-1))' |
(?:subexpression) | Defines a noncapturing group. | Write(?:Line)? | 'WriteLine' in 'Console.WriteLine()''Write' in 'Console.Write(value)' |
(?imnsx-imnsx:subexpression) | Applies or disables the specified options within subexpression. For more information, see Regular Expression Options. | Ad{2}(?i:w+)b | 'A12xl', 'A12XL' in 'A12xl A12XL a12xl' |
(?=subexpression) | Zero-width positive lookahead assertion. | bw+b(?=.+and.+) | 'cats', 'dogs'in 'cats, dogs and some mice.' |
(?!subexpression) | Zero-width negative lookahead assertion. | bw+b(?!.+and.+) | 'and', 'some', 'mice'in 'cats, dogs and some mice.' |
(?<=subexpression) | Zero-width positive lookbehind assertion. | bw+b(?<=.+and.+)——————————— bw+b(?<=.+and.*) | 'some', 'mice'in 'cats, dogs and some mice.'———————————— 'and', 'some', 'mice'in 'cats, dogs and some mice.' |
(?<!subexpression) | Zero-width negative lookbehind assertion. | bw+b(?<!.+and.+)——————————— bw+b(?<!.+and.*) | 'cats', 'dogs', 'and'in 'cats, dogs and some mice.'———————————— 'cats', 'dogs'in 'cats, dogs and some mice.' |
(?>subexpression) | Atomic group. | (?>a|ab)c | 'ac' in'ac'nothing in 'abc' |
Lookarounds at a glance
When the regular expression engine hits a lookaround expression, it takes a substring reaching from the current position to the start (lookbehind) or end (lookahead) of the original string, and then runsRegex.IsMatch on that substring using the lookaround pattern. Success of this subexpression's result is then determined by whether it's a positive or negative assertion.
| Lookaround | Name | Function |
|---|---|---|
(?=check) | Positive Lookahead | Asserts that what immediately follows the current position in the string is 'check' |
(?<=check) | Positive Lookbehind | Asserts that what immediately precedes the current position in the string is 'check' |
(?!check) | Negative Lookahead | Asserts that what immediately follows the current position in the string is not 'check' |
(?<!check) | Negative Lookbehind | Asserts that what immediately precedes the current position in the string is not 'check' |
Once they have matched, atomic groups won't be re-evaluated again, even when the remainder of the pattern fails due to the match. This can significantly improve performance when quantifiers occur within the atomic group or the remainder of the pattern.
Quantifiers
A quantifier specifies how many instances of the previous element (which can be a character, a group, or a character class) must be present in the input string for a match to occur. Quantifiers include the language elements listed in the following table. For more information, see Quantifiers.
| Quantifier | Description | Pattern | Matches |
|---|---|---|---|
* | Matches the previous element zero or more times. | d*.d | '.0', '19.9', '219.9' |
+ | Matches the previous element one or more times. | 'be+' | 'bee' in 'been', 'be' in 'bent' |
? | Matches the previous element zero or one time. | 'rai?n' | 'ran', 'rain' |
{n} | Matches the previous element exactly n times. | ',d{3}' | ',043' in '1,043.6', ',876', ',543', and ',210' in '9,876,543,210' |
{n,} | Matches the previous element at least n times. | 'd{2,}' | '166', '29', '1930' |
{n,m} | Matches the previous element at least n times, but no more than m times. | 'd{3,5}' | '166', '17668''19302' in '193024' |
*? | Matches the previous element zero or more times, but as few times as possible. | d*?.d | '.0', '19.9', '219.9' |
+? | Matches the previous element one or more times, but as few times as possible. | 'be+?' | 'be' in 'been', 'be' in 'bent' |
?? | Matches the previous element zero or one time, but as few times as possible. | 'rai??n' | 'ran', 'rain' |
{n}? | Matches the preceding element exactly n times. | ',d{3}?' | ',043' in '1,043.6', ',876', ',543', and ',210' in '9,876,543,210' |
{n,}? | Matches the previous element at least n times, but as few times as possible. | 'd{2,}?' | '166', '29', '1930' |
{n,m}? | Matches the previous element between n and m times, but as few times as possible. | 'd{3,5}?' | '166', '17668''193', '024' in '193024' |
Backreference Constructs
A backreference allows a previously matched subexpression to be identified subsequently in the same regular expression. The following table lists the backreference constructs supported by regular expressions in .NET. For more information, see Backreference Constructs.
| Backreference construct | Description | Pattern | Matches |
|---|---|---|---|
number | Backreference. Matches the value of a numbered subexpression. | (w)1 | 'ee' in 'seek' |
k<name> | Named backreference. Matches the value of a named expression. | (?<char>w)k<char> | 'ee' in 'seek' |
Alternation Constructs
Alternation constructs modify a regular expression to enable either/or matching. These constructs include the language elements listed in the following table. For more information, see Alternation Constructs.
| Alternation construct | Description | Pattern | Matches |
|---|---|---|---|
| | Matches any one element separated by the vertical bar (|) character. | th(e|is|at) | 'the', 'this' in 'this is the day.' |
(?(expression)yes|no) | Matches yes if the regular expression pattern designated by expression matches; otherwise, matches the optional no part. expression is interpreted as a zero-width assertion. | (?(A)Ad{2}b|bd{3}b) | 'A10', '910' in 'A10 C103 910' |
(?(name)yes|no) | Matches yes if name, a named or numbered capturing group, has a match; otherwise, matches the optional no. | (?<quoted>')?(?(quoted).+?'|S+s) | 'Dogs.jpg ', 'Yiska playing.jpg' in 'Dogs.jpg 'Yiska playing.jpg' |
Substitutions
Substitutions are regular expression language elements that are supported in replacement patterns. For more information, see Substitutions. The metacharacters listed in the following table are atomic zero-width assertions.
| Character | Description | Pattern | Replacement pattern | Input string | Result string |
|---|---|---|---|---|---|
$number | Substitutes the substring matched by group number. | b(w+)(s)(w+)b | $3$2$1 | 'one two' | 'two one' |
${name} | Substitutes the substring matched by the named group name. | b(?<word1>w+)(s)(?<word2>w+)b | ${word2} ${word1} | 'one two' | 'two one' |
$$ | Substitutes a literal '$'. | b(d+)s?USD | $$$1 | '103 USD' | '$103' |
$& | Substitutes a copy of the whole match. | $?d*.?d+ | **$&** | '$1.30' | '**$1.30**' |
$` | Substitutes all the text of the input string before the match. | B+ | $` | 'AABBCC' | 'AAAACC' |
$' | Substitutes all the text of the input string after the match. | B+ | $' | 'AABBCC' | 'AACCCC' |
$+ | Substitutes the last group that was captured. | B+(C+) | $+ | 'AABBCCDD' | 'AACCDD' |
$_ | Substitutes the entire input string. | B+ | $_ | 'AABBCC' | 'AAAABBCCCC' |
Regular Expression Options
You can specify options that control how the regular expression engine interprets a regular expression pattern. Many of these options can be specified either inline (in the regular expression pattern) or as one or more RegexOptions constants. This quick reference lists only inline options. For more information about inline and RegexOptions options, see the article Regular Expression Options.
You can specify an inline option in two ways: Download internet explorer 10 for mac.
- By using the miscellaneous construct
(?imnsx-imnsx), where a minus sign (-) before an option or set of options turns those options off. For example,(?i-mn)turns case-insensitive matching (i) on, turns multiline mode (m) off, and turns unnamed group captures (n) off. The option applies to the regular expression pattern from the point at which the option is defined, and is effective either to the end of the pattern or to the point where another construct reverses the option. - By using the grouping construct
(?imnsx-imnsx:subexpression), which defines options for the specified group only.
The .NET regular expression engine supports the following inline options:
| Option | Description | Pattern | Matches |
|---|---|---|---|
i | Use case-insensitive matching. | b(?i)a(?-i)aw+b | 'aardvark', 'aaaAuto' in 'aardvark AAAuto aaaAuto Adam breakfast' |
m | Use multiline mode. ^ and $ match the beginning and end of a line, instead of the beginning and end of a string. | For an example, see the 'Multiline Mode' section in Regular Expression Options. | |
n | Do not capture unnamed groups. | For an example, see the 'Explicit Captures Only' section in Regular Expression Options. | |
s | Use single-line mode. | For an example, see the 'Single-line Mode' section in Regular Expression Options. | |
x | Ignore unescaped white space in the regular expression pattern. | b(?x) d+ s w+ | '1 aardvark', '2 cats' in '1 aardvark 2 cats IV centurions' |
Miscellaneous Constructs
Miscellaneous constructs either modify a regular expression pattern or provide information about it. The following table lists the miscellaneous constructs supported by .NET. For more information, see Miscellaneous Constructs.
| Construct | Definition | Example |
|---|---|---|
(?imnsx-imnsx) | Sets or disables options such as case insensitivity in the middle of a pattern.For more information, see Regular Expression Options. | bA(?i)bw+b matches 'ABA', 'Able' in 'ABA Able Act' |
(?#comment) | Inline comment. The comment ends at the first closing parenthesis. | bA(?#Matches words starting with A)w+b |
# [to end of line] | X-mode comment. The comment starts at an unescaped # and continues to the end of the line. | (?x)bAw+b#Matches words starting with A |
See also
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.
Image from xkcd.com, slightly altered
- 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. 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.
Powershell Regular Expression Cheat Sheet Answers
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.
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.
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.
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
Regex Cheat Sheet Pdf
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.
When you use the -match operator, an automatic variable called $matches contains the results of the match. Free download gift certificate template for mac. 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. Adobe photoshop elements 13 download for mac. 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.
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.
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.
Regular Expression Powershell
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()
The [Regex] object method Matches is the other option.
When using Pester tests, the Should Match uses a regular expression.
Powershell Regular Expression Match Digit
When with Pester is the exception to the rule of not using [regex]::Escape(). Pester does not have a substring match alternative.
Regex Cheat Sheet
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 Example
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.
