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

使用Select-String匹配字符串并按出现顺序返回结果数组的问题

PowerShell多模式匹配按出现顺序返回结果数组实现方案

实现核心是给Select-String追加-AllMatches参数,默认Select-String仅返回每行第一个匹配项,添加该参数后会捕获同一输入内的所有匹配结果,再提取匹配值即可得到按出现顺序排列的数组。

完整示例代码

1. 定义测试字符串

$string = "My car is Yellow but my car seat is White. I ate Yellow Banana, Yellow lemon and White peach."

2. 执行匹配命令

# 输出结果直接为按出现顺序排序的数组
$resultArray = Select-String -InputObject $string -Pattern 'Yellow', 'White' -AllMatches | ForEach-Object { $_.Matches.Value }

3. 输出验证

直接输出$resultArray即可得到期望的顺序结果:

Yellow
White
Yellow
Yellow
White

补充说明

  • 提取的$_.Matches.Value默认按匹配先后顺序排列,无需额外排序操作
  • 可通过$resultArray -is [array]验证返回对象为数组类型,返回值为True

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 13:45:03