2

Given a database type string of varchar(30), I would like to standardize it for SQL Server by capitalizing the type name and putting it in brackets. The desired result is [VARCHAR](30).

How can I convert $1 to uppercase? This expression identifies the type and adds brackets, but is does not ToUpper().

PS> "varchar(30)" -replace '^\[*(\w+)\]*(.*)','[$1]$2'
[varchar](30)
mklement0
  • 382,024
  • 64
  • 607
  • 775
lit
  • 14,456
  • 10
  • 65
  • 119

2 Answers2

2

Using a simplified version of your regex:

In PowerShell [Core] v6.1+:

PSCore> 'varchar(30)' -replace '^\[*\w+\]*', { '[' + $_.Value.ToUpper() + ']' }
[VARCHAR](30)

Note: If there can be at most one [...] enclosure in the input, \[? and \]? should be used instead.

In Windows PowerShell:

WinPS> [regex]::Replace('varchar(30)', '^\[*\w+\]*', { param($m) '[' + $m.Value.ToUpper() + ']' })
[VARCHAR](30)

For background information, see this answer.

mklement0
  • 382,024
  • 64
  • 607
  • 775
0

here is a very slightly different way that uses the $Matches automatic variable and the -f string format operator. [grin]

it makes a few presumptions about the input data, but not as serious as presuming varchar is the only word you want to convert to all-caps. those are ...

  • the stuff you want as ALLCAPS is everything up to the 1st (
  • the remainder is to be kept as is
  • the 1st part is to be enclosed in brackets []

the code ...

# fake reading in a text file
#    in real life use Get-Content
$InStuff = @'
varchar(30)
OtherThing(21)
santa(666)
ALREADYALLCAPS(97531)
'@ -split [System.Environment]::NewLine

foreach ($IS_Item in $InStuff)
    {
    $Null = $IS_Item -match '(.+)(\(.+)'
    '[{0}]{1}' -f $Matches[1].ToUpper(), $Matches[2]
    }

output ...

[VARCHAR](30)
[OTHERTHING](21)
[SANTA](666)
[ALREADYALLCAPS](97531)
Lee_Dailey
  • 7,292
  • 2
  • 22
  • 26
  • Thanks, @Lee_Dailey. I was using $Matches before after doing a `-match` operation. I forgot that I could just produce the string from $Matches, so I was repeating the regex in a `-replace`. – lit Jan 27 '20 at 20:25
  • @lit - you are most welcome! [*grin*] i tried to use `-replace` and gave up since i wanted to manipulate things without too many awkward steps. [*grin*] – Lee_Dailey Jan 27 '20 at 21:51