Regular Expressions regex

Powershell .replace vs -replace

"text string" -replace uses regular expressions

$string.replace() does not

get-help -Full about_reg* | less -i 

Export data from active directory

ldifde -d "OU=Apps,DC=blah,DC=corp" -f h:\blah.ldf -s blah.corp -l objectClass,cn,SamAccountName,displayName,description,member 

Modify an ldif export

$InputLDifFile = "H:\blah.ldf"

$OutputLDifFile = "H:\blah.ldf"

$originalString = "DC=blah,DC=corp"

$replacementString = "DC=blah,DC=dev"

#The string could have a newline and space breaking it apart

$originalString = $originalString -replace '.', '$&\r?\n?\s?'

#remove the last newline space from the search string

$originalString = $originalString.Substring(0, $($originalString.Length - 9))

Get-Content $InputLDifFile  | out-string | foreach {$_ -replace $originalString, $replacementString} | set-content $OutputLDifFile

 

 These 2 lines do the same thing.

$originalString -replace '[\w\W+]', '$&\r?\n?\s?'

$originalString -replace '.', '$&\r?\n?\s?'

Notes on multiline replace 

http://powershell.com/cs/blogs/ebook/archive/2009/03/30/chapter-13-text-and-regular-expressions.aspx

$string ="blah blah blah b706420s01 blah  b244110s01  " ($string | Select-String -Pattern "b\d{2}......." -AllMatches).matches  Case sensitive [regex]::matches("B550410S01 B777410S01","B\d{2}.......")  [regex]::matches("B550410S01 B777410S01","[bB]\d{2}.......")

Replace everything after -

"this is a - test blah blah blah" -replace "-[A-Za-z0-9\s]*"

("this is a - test blah blah blah" -split "-")[0]

"AWS-accountname-Admin-1234567890123" -replace "(?i)^aws-([^\-]+)-([^\-]+)-([\d]{12,})", "`$3,`$1,`$2"

(?i)  ignore case

^AWS- starts with aws

([^\-]+) capture any character that is not a dash and store in $1

    [^]      Matches any characters except those in brackets.

    \        Matches the character that follows as an escaped character

    +        Matches repeating instances of the preceding characters.

-

([^\-]+) capture any character that is not a dash and store in $2

    [^]      Matches any characters except those in brackets.

    \        Matches the character that follows as an escaped character

    +        Matches repeating instances of the preceding characters.

-

([\d]{12,}) capture any digits 12 or more ans store in $3

    \d       Matches any decimal digit.

    {n,}     Specifies at least n matches

gitlab project name

Path can contain only letters, digits, '_', '-' and '.'. Cannot start with '-', end in '.git' or end in '.atom' 

 

[ValidatePattern('^[a-zA-Z0-9_][a-zA-Z0-9\-_\.]*[^(\.atom|\.git)]$')]$ProjectName = "-gitproject.foo"

"web1foosite2" -match '^(?<class>[a-zA-Z]{1,})(?<id>[0-9]{1,})(?<domain>[a-zA-Z]{1,})(?<site>[a-zA-Z]{3}[0-9])$'

$matches