You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell中如何对字符串数组内的数字进行分组?

PowerShell 实现连续数字分组

可以自己实现一个函数来完成这个需求,核心逻辑是遍历数组,识别连续递增的数字序列并合并格式。以下是具体实现:

function Group-ConsecutiveNumbers {
    param(
        [Parameter(Mandatory=$true)]
        [string[]]$InputArray
    )

    # 将输入字符串数组转换为整数数组,过滤无效数字
    $numbers = $InputArray | ForEach-Object { if ($_ -match '^\d+$') { [int]$_ } } | Where-Object { $_ -ne $null }
    if (-not $numbers) { return @() }

    $result = @()
    $currentStart = $numbers[0]
    $currentEnd = $numbers[0]

    for ($i = 1; $i -lt $numbers.Count; $i++) {
        if ($numbers[$i] -eq $currentEnd + 1) {
            # 当前数字与上一个连续,更新结束值
            $currentEnd = $numbers[$i]
        } else {
            # 不连续,将当前组加入结果
            $result += if ($currentStart -eq $currentEnd) { "$currentStart" } else { "$currentStart..$currentEnd" }
            # 重置当前组的起始和结束
            $currentStart = $numbers[$i]
            $currentEnd = $numbers[$i]
        }
    }

    # 处理最后一个组
    $result += if ($currentStart -eq $currentEnd) { "$currentStart" } else { "$currentStart..$currentEnd" }

    return $result
}

示例用法

# 输入目标字符串数组
$inputArray = '4', '7', '8', '9', '10', '21', '25', '26', '27'

# 调用分组函数
$groupedArray = Group-ConsecutiveNumbers -InputArray $inputArray

# 按要求格式输出结果
$groupedArray | ForEach-Object {
    Write-Host "Array[$($groupedArray.IndexOf($_))] = `"$_`""
}

输出结果

Array[0] = "4"
Array[1] = "7..10"
Array[2] = "21"
Array[3] = "25..27"

说明

  • 函数会自动过滤输入中的非数字元素,避免格式错误
  • 遍历过程中实时跟踪连续序列的起止值,遇到断点时立即格式化当前序列并保存
  • 最后处理剩余的未闭合序列,确保所有元素都被正确分组

内容的提问来源于stack exchange,提问作者HalfBit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 16:39:59