首页 > 解决方案 > 如何通过组数组的值在 PowerShell 中对正则表达式匹配进行排序

问题描述

我有一个字符串数组,每个字符串都包含一个代表 sprint(scrum)编号的数字。现在,我想在 Powershell 中使用正则表达式按 sprint 编号对数组进行排序。

数组示例

# define the array
$a = @("a.sprint-100","a.sprint-99","a.sprint-49","a.sprint-98")

# escape hard defined string in regex
$escapedString = [regex]::escape(".sprint-")

# create regex which matches <AnyCharacter>.sprint-<SprintNumber>
[regex]$regex = "(.+)$escapedString([0-9]{2,3})"

# process the regex on all strings and print out the sprint number
$a | %{[System.Text.RegularExpressions.Regex]::Match($_, $regex)} | %{$_.Groups[2].value}

# output: 100 99 49 98

# but my sort logic doesn't work
 $a | %{[System.Text.RegularExpressions.Regex]::Match($_, $regex)} | Sort-Object -Property {$_.Groups[2].value} -Descending | %{$_.Groups[2].value}

# output: 99 98 49 100

我正在对字符串进行排序。所以,这可能是主要问题。有人知道将匹配值解析为int吗?

如果我尝试这样做,那么我会得到'value' is a ReadOnly property.". 还是有更好的方法来获得我想要的排序结果?

为了简单起见,我在这里使用了一个字符串数组。但在实际场景中,它是一个数组,包含带有一堆数据的自定义对象。这个数组应该在我的正则表达式管道之后排序。

提前致谢!

标签: regexpowershell

解决方案


您需要对字符串的数字部分进行排序,转换为[int]first,否则,排序仍然是字母数字:

# define the array
$a = "a.sprint-100","a.sprint-99","a.sprint-49","a.sprint-98"
# sort on the numeric part of the strings, converted to [int]
$a | Sort-Object {[int]($_ -split '-')[-1]}

结果:

a.sprint-49
a.sprint-98
a.sprint-99
a.sprint-100

推荐阅读