Thomas
Thomas

Reputation: 1208

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?

Upvotes: 1

Views: 858

Answers (3)

js2010
js2010

Reputation: 27566

Or replace everything before the "@" sign with nothing:

'[email protected]' -replace '.*@'

domain.s483.hgy.i.lo.uk

Upvotes: 1

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174845

If you want to split on the first character of @domain. but without removing "domain.", use the -split regex operator with a lookahead assertion instead:

("[email protected]" -split "@(?=domain\.)")[-1]

See JosefZ's excellent answer for how to force PowerShell to pick the correct String.Split() overload, although it won't help you preserve the domain. part

Upvotes: 2

JosefZ
JosefZ

Reputation: 30218

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)

Upvotes: 2

Related Questions