1

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

So for example:

"some_user@domain.s483.hgy.i.lo.uk".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?

Lance U. Matthews
  • 15,725
  • 6
  • 48
  • 68
Thomas
  • 1,199
  • 3
  • 13
  • 25
  • Take a look at the result of just `"some_user@domain.s483.hgy.i.lo.uk".split("@domain.")` and then consider that [`Split()`](https://learn.microsoft.com/dotnet/api/system.string.split#System_String_Split_System_Char___) takes an array of characters on which any will cause a split, not an exact sequence of characters on which to split. – Lance U. Matthews Apr 15 '20 at 18:56
  • 1
    Use `-split` operator for this --> `('some_user@domain.s483.hgy.i.lo.uk' -split '@domain\.')[-1]` – AdminOfThings Apr 15 '20 at 18:56
  • 1
    Does this answer your question? [Strange result from String.Split()](https://stackoverflow.com/questions/40414946/strange-result-from-string-split). See the note in [@mklement0's answer](https://stackoverflow.com/a/40415484/150605): "the .NET Core `String.Split()` method now _does_ have a scalar `[string]` overload that looks for an entire string as the separator, which PowerShell Core selects _by default_..." – Lance U. Matthews Apr 15 '20 at 19:03

3 Answers3

2

Use -split operator as follows:

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

If you insist upon the Split() method then use

 "some_user@domain.s483.hgy.i.lo.uk".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)
JosefZ
  • 28,460
  • 5
  • 44
  • 83
2

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:

("some_user@domain.s483.hgy.i.lo.uk" -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

Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
1

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

'some_user@domain.s483.hgy.i.lo.uk' -replace '.*@'

domain.s483.hgy.i.lo.uk
js2010
  • 23,033
  • 6
  • 64
  • 66