Search code examples
powershellsplitpowershell-5.0powershell-coreemail-address

Powershell split not returning expected result


Powershell 5.1.1 returns an unexpected result when I use the split function on a string.

So for example:

"[email protected]".split("@domain.")[-1]
>> uk

I would expect to see domain.hgy.i.lo.uk and not uk!

Is this a bug or am I missing something here? This appears to work on later versions of powershell. Can someone explain?


Solution

  • Use -split operator as follows:

    "[email protected]" -split [regex]::Escape("@domain.")
    
    some_user
    s483.hgy.i.lo.uk
    

    If you insist upon the Split() method then use

     "[email protected]".Split([string[]]'@domain.',[System.StringSplitOptions]::None)
    
    some_user
    s483.hgy.i.lo.uk
    

    The latter is based on familiarity with a list of the different sets of arguments that can be used with Split() method:

    ''.split
    
    OverloadDefinitions
    -------------------
    string[] Split(Params char[] separator)
    string[] Split(char[] separator, int count)
    string[] Split(char[] separator, System.StringSplitOptions options)
    string[] Split(char[] separator, int count, System.StringSplitOptions options)
    string[] Split(string[] separator, System.StringSplitOptions options)
    string[] Split(string[] separator, int count, System.StringSplitOptions options)