regex - 如何通过组数组的值在 PowerShell 中对正则表达式匹配进行排序
问题描述
我有一个字符串数组,每个字符串都包含一个代表 sprint(scrum)编号的数字。现在,我想在 Powershell 中使用正则表达式按 sprint 编号对数组进行排序。
数组示例
- a.sprint-100
- a.sprint-99
- a.sprint-49
- a.sprint-98
# 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."
. 还是有更好的方法来获得我想要的排序结果?
为了简单起见,我在这里使用了一个字符串数组。但在实际场景中,它是一个数组,包含带有一堆数据的自定义对象。这个数组应该在我的正则表达式管道之后排序。
提前致谢!
解决方案
您需要对字符串的数字部分进行排序,转换为[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
推荐阅读
- database - 如何在 Visual Studio 的 C++/CLR 项目中使用数据库?
- python - 如何检查熊猫数据框中的列之间的冲突?
- python - 如何使用 PySpark 将分层 CSV 文件转换为 ADB 中的表
- python - 字典中numpy数组列的Python min/max
- android - 如何在没有背景噪音的情况下录制音频(心音)(例如:车辆声音、电视声音)
- kubernetes - 为什么 Kubernetes 中的 pod 会自动挂载服务帐户密钥?
- mysql - 如何一次从所有表中选择?
- sql - 两个元组之间的 SQL 索引,AND 条件
- reactjs - 尝试使用 redux-thunk,但它显示错误,即使对我来说一切都很好
- postgresql - 返回诗的总数,提到死亡的诗和提到爱的诗的平均字符数