Replace first and last character to Upper case in PowerShell

Blue412 21 Reputation points
2021-12-20T14:46:24.053+00:00

Can we change the first and last characters to uppercase? Something like the below output? TitleCase works to change the first character to uppercase, was stuck on the last character. Any help is appreciated :)

Input: Servername01

Desired Output: ServernamE01

Windows for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 47,901 Reputation points
    2021-12-20T15:45:56.673+00:00

    I really wish Microsoft actually supported the PCRE regex code. Sadly, it does not.

    Your request (pretty easily handled in other languages) could be done like this:

    $s -replace '^([a-z])(.+)([a-z])(\d\d)$', '\U$1\E$2\U$3\E$4'
    

    Where "/U" says to convert characters that follow to uppercase, and "/E" says to cease the conversion.

    Unfortunately, you'll have to resort to other means to accomplish this:

    $s -match '^([a-z])(.+)([a-z])(\d\d)$'
    $u = "{0}{1}{2}{3}" -f $matches[1].ToUpper(), $matches[2], $matches[3].ToUpper(), $matches[4]
    

    It does the same thing, but the replacement happens outside the regex. :-(

    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Blue412 21 Reputation points
    2021-12-21T14:54:51.407+00:00

    @Rich Matheisen Yeah, agree on that point, but the mentioned approach defeats the purpose when we have a undefined character count in the server name and can't specify the exact match count.

    I tried trimming the last char in the string and writing the output to two variables. Then capturing the last char with substring and length approach to new variable and then making it uppercase and finally joining them

    $input = 'servername'
    $pattern = (get-culture).textinfo
    $result = $pattern.totitlecase($input.ToLower())
    $rest_char = $result.Substring(0,$result.Length-1)
    $final_char = ($result.Substring($result.Length-1)).toupper()
    $final_result = $rest_char+$final_char

    Might be a dumb approach, but got the job done. Just looking for some pointers, if i can do this better way?

    Thanks :)


  2. Blue412 21 Reputation points
    2021-12-21T16:24:13.387+00:00

    @DaveK and @Rich Matheisen thanks for the input. We only have either a single or double digit in the end of servername and this one addressed it.

    $s -match '^([a-z])(.+)([a-z])(\d+)$'
    $u = "{0}{1}{2}{3}" -f $matches[1].ToUpper(), $matches[2], $matches[3].ToUpper(), $matches[4].ToUpper()

    Thanks.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.