Powershell带下划线的字符串排序

bre*_*tth 12 sorting powershell stringcomparer

以下列表未正确排序(恕我直言):

$a = @( 'ABCZ', 'ABC_', 'ABCA' )
$a | sort
ABC_
ABCA
ABCZ
Run Code Online (Sandbox Code Playgroud)

我方便的ASCII图表和Unicode C0控件和基本拉丁图表的下划线(低线)的序数为95(U + 005F).这是一个比大写字母AZ更高的数字.排序应该将字符串以下划线结尾.

Get-Culture是en-US

下一组命令符合我的期望:

$a = @( 'ABCZ', 'ABC_', 'ABCA' )
[System.Collections.ArrayList] $al = $a
$al.Sort( [System.StringComparer]::Ordinal )
$al
ABCA
ABCZ
ABC_
Run Code Online (Sandbox Code Playgroud)

现在我创建一个包含相同3个字符串的ANSI编码文件:

Get-Content -Encoding Byte data.txt
65 66 67 90 13 10  65 66 67 95 13 10  65 66 67 65 13 10
$a = Get-Content data.txt
[System.Collections.ArrayList] $al = $a
$al.Sort( [System.StringComparer]::Ordinal )
$al
ABC_
ABCA
ABCZ
Run Code Online (Sandbox Code Playgroud)

包含下划线/下线的字符串不再正确排序.我错过了什么?


编辑:

让我们参考这个例子#4:

'A' -lt '_'
False
[char] 'A' -lt [char] '_'
True
Run Code Online (Sandbox Code Playgroud)

似乎两个语句都应该为False或两者都应为True.我在第一个语句中比较字符串,然后比较Char类型.字符串只是Char类型的集合,所以我认为两个比较操作应该是等价的.

现在例如#5:

Get-Content -Encoding Byte data.txt
65 66 67 90 13 10  65 66 67 95 13 10  65 66 67 65 13 10
$a = Get-Content data.txt
$b = @( 'ABCZ', 'ABC_', 'ABCA' )
$a[0] -eq $b[0]; $a[1] -eq $b[1]; $a[2] -eq $b[2];
True
True
True
[System.Collections.ArrayList] $al = $a
[System.Collections.ArrayList] $bl = $b
$al[0] -eq $bl[0]; $al[1] -eq $bl[1]; $al[2] -eq $bl[2];
True
True
True
$al.Sort( [System.StringComparer]::Ordinal )
$bl.Sort( [System.StringComparer]::Ordinal )
$al
ABC_
ABCA
ABCZ
$bl
ABCA
ABCZ
ABC_
Run Code Online (Sandbox Code Playgroud)

两个ArrayList包含相同的字符串,但排序方式不同.为什么?

Bra*_*ing 0

Windows 使用 Unicode,而不是 ASCII,因此您看到的是 en-US 的 Unicode 排序顺序。排序的一般规则是:

  1. 数字,然后小写和大写混合
  2. 特殊字符出现在数字之前。

扩展你的例子,

$a = @( 'ABCZ', 'ABC_', 'ABCA', 'ABC4', 'abca' )

$a | sort-object
ABC_
ABC4
abca
ABCA
ABCZ
Run Code Online (Sandbox Code Playgroud)