PowerShell: Regular Expressions Cheat Sheet

Below is a regular expression list

.matches any character except newline
\escape character
\wword character [a-zA-Z_0-9]
\Wnon-word character [^a-zA-Z_0-9]
\dDigit [0-9]
\Dnon-digit [^0-9]
\nnew line
\rcarriage return
\swhite space
\Snon-white space
^beginning of a line
$end of a line
\Abeginning of the string (multi-line match)
\Zend of the string (multi-line match)
\bword boundary, boundary between \w and \W
\Bnot a word boundary
\<beginning of a word
\>end of a word
{n}matches exaclty n times
{n,}matches a minimum of n times
{x,y}matches a min of x and max of y
(a|b)‘a’ or ‘b’
*matches 0 or more times
+matches 1 or more times
?matches 1 or 0 times
*?matches 0 or more times, but as few as possible
+?matches 1 or more times, but as few as possible
??matches 0 or 1 time
#Match while tagging match groups 
'CowColour Brown' -match '(?<Attribute>\w+) (?<Value>\w+)' | out-null $matches.Attribute $matches.Value 
#Matching groups - your $matches object will have properties containing the valid matches 
"Subnet:" -match 'Subnet:(?<SiteSubnet>(?:\d{1,3}\.){3}\d{1,3}/\d+)'
#Replace to reformat a string 
'This is a wild test' -replace '.*(w[^ ]+).*','Not so $1' 
#Not so wild
#Lazy matching (to prevent over-matching) use a ? after the + or * 
"<h1>MyHeading</h1>" -replace '<([^/]+?)>','<cow>' -replace '</([^/]+?)>','</cow>' 
#negative lookbehind 
($DistinguishedName -split '(?<!\\),')[1..100] -join ','

Leave a Reply

Your email address will not be published. Required fields are marked *