stringpowershellsplitpowershell-7

Weird behaviors around "." string manipulation in PowerShell


I'm using PowerShell 7.4.5.

First example: 'a.b' -split '.' does not give you a two-element array of a and b, but a four-element array of empty strings.

Another example is 'rodtipsqleastus2.database.windows.net'.TrimStart('rodtipsqleastus2.'). It doesn't give you database.windows.net but base.windows.net instead.

Could someone throw some light here? Thanks.


Solution

  • Regarding your first issue: PowerShell's split uses regular expression matching by default, cf. about_Split

    RegexMatch: Use regular expression matching to evaluate the delimiter. This is the default behavior.

    Use

    'a.b' -split '.', 0, 'simplematch'
    

    Note the additional , 0 as

    You can use options, such as SimpleMatch, only when the Max-substrings value is specified.

    Regarding your second issue: Assuming this uses .NET's TrimStart, this one takes an array of characters, not a 1:1 string, cf. TrimStart(Char[]).

    That means

    TrimStart('rodtipsqleastus2.')
    

    will remove all subsequent "r"s, "o"s, "d"s, "t"s and so on until it finds the first character not in that list. Which in your case is the "b".

    Not sure what would be the best solution, maybe

    'rodtipsqleastus2.database.windows.net'.Substring(17)
    

    does the trick for you.