My Technical Notes

Monday, 15 December 2014

Use of Regex Replace method

I needed to replace all instances of `a.AddressLineX` with `COALESCE(a.AddressLineX, '')`. Here is the code I came up with:


$v = Get-CB
# $v now contains the contents of the clipboard which was:
# a.AddressLine1 + ' ' + a.AddressLine2 + ' ' + a.AddressLine3 + ' ' + a.AddressLine4
[Regex]::Replace($v, "(a.AddressLine[\d])", 'COALESCE(${1}, '''')')
COALESCE(a.AddressLine1, '') + ' ' + COALESCE(a.AddressLine2, '') + ' ' + COALESCE(a.AddressLine3, '') + ' ' + COALESCE(a.AddressLine4, '')

A few things to note: `${1}` can be replaced with `$1`, but it is handy to remember because we might want to write a digit after the group, so we write `${1}1`, not `$11`. Secondly, in PowerShell, to escape the single quote character, we double them up, like in SQL.

No comments: