PowerShell: dates and -replace

I sometimes need to do a naive replacement of dates in a typical UK format to a typical US format.

For example, I might want to take

The Battle of Hastings took place on 14/10/1066 between Harold and William. The war between the 2 was triggered by Edward the Confessor’s death on 12/06/1066.

, and convert it to:

The Battle of Hastings took place on 10/14/1066 between Harold and William. The war between the 2 was triggered by Edward the Confessor’s death on 06/12/1066

or to…

The Battle of Hastings took place on 10-14-1066 between Harold and William. The war between the 2 was triggered by Edward the Confessor’s death on 06-12-1066

This line achieves the second transformation, assuming the text is in history.txt. Note the single quotes.

$(Get-Content -Path .\history.txt) -replace '([0-9]{2})/+([0-9]{2})/+([0-9]{4})','$2-$1-$3'

psregex02

Gist.

Credit to Don Jones for a similar example.

NotePad++: ¬†As this is essentially Regex after all, I will mention that you can do the same kind of thing in NotePad++ and indeed in anything that has a Regex capability. The NotePad++ case looks like this, where the “Find what” pattern is exactly as for PowerShell, and the “Replace with” differs a bit: [\2/\1/\3]

psregex03

Advertisements

PowerShell: regex

psregex01

psregex02

cd C:\Sandbox\PowerShell
# this returns true
 $regex = [regex]"xxx"
 $regex.IsMatch("xxx")
# both the next match because {u?} means that u may occur, or may not occur
 $regex = [regex] "colou?r"
 $regex.IsMatch("color")
 $regex.IsMatch("colour")
# both match because { (i|e) ) means that those are mandatory alternatives at that character position
 $regex = [regex]"art(i|e)fact"
 $regex.IsMatch("artefact")
 $regex.IsMatch("artifact")

Running a regex on dates is far more involved. My advice would be to write a .net class/method, and or a date tryparse, with the challenging bit often being the locale and the many possible formats.

Removing blank lines (not strictly PowerShell)

[\n\r]+$