Powershell: Enhance the -split operator with negative maximum token counts to split from the end

Created on 7 Sep 2017  路  6Comments  路  Source: PowerShell/PowerShell

As approved in https://github.com/PowerShell/PowerShell/pull/4721#issuecomment-327636502, and later amended in https://github.com/PowerShell/PowerShell/pull/5125#discussion_r144723267:

After the enhancement, only a <Max-substrings> value of 0 will be accepted as the explicit signal that _all_ tokens should be returned, however many are found in the input string(s).

Negative <Max-substrings> values will work analogously to the already supported positive values, except that:

  • they return the specified number of strings from the _end_ of the string(s).

  • all individually extracted tokens are returned in input order, and whatever unsplit part remains, if any, is returned as the _first_ token.

Examples:

PS> 'a b c d' -split ' ', -2  # split into (at most) 2 strings from the end
a b c  # prefix
d        # requested token

PS> 'a b c d' -split ' ', -3  # split into (at most) 3 strings from the end
a b   # prefix
c       
d 

PS> 'a b' -split ' ', -2  # 2 resulting strings - complete split; same as 0 in this case
a
b

Note that both -split ' ', 1 and -split ' ', -1 are _no-ops_: they request no splitting at all, and the sign of the <Max-substrings> argument is therefore irrelevant.

Reporting the prefix (unsplit part) first enables the following idiom:

PS> $prefix, $tokens = 'a b c d' -split ' ', -3 # -> $prefix = 'a b', $tokens = 'c', 'd'

Environment data

PowerShell Core v6.0.0-beta.8
Breaking-Change Committee-Reviewed Hacktoberfest Issue-Enhancement Resolution-Fixed Up-for-Grabs WG-Language

Most helpful comment

This is being worked on by a student (@ece-jacob-scott) at HackIllinois! 馃帀

All 6 comments

@SteveL-MSFT Can we mark by 'Committee-Reviewed'?

@PowerShell/powershell-committee had reviewed this as part of #4721 and agree this is a useful enhancement and a breaking change not likely to impact anyone. Documentation will need to be updated.

@SteveL-MSFT We need re-approve by PowerShell-Committee.

@iSazonov I don't think the small change in behavior necessitates a committee review as the main aspect that committee approved is having a breaking change. I think the code review feedback is sufficient on the changed design as long as it's documented appropriately.

This is being worked on by a student (@ece-jacob-scott) at HackIllinois! 馃帀

:tada:This issue was addressed in #8960, which has now been successfully released as v7.0.0-preview.2.:tada:

Handy links:

Was this page helpful?
0 / 5 - 0 ratings