比较数组的字符串与数组的另一个字符串

问题描述 投票:0回答:1

我正在尝试将一个数组中的字符串与另一个数组中的另一个字符串进行比较

我觉得逻辑是对的,但由于某种原因无法得到预期的输出

数组$groupslist的值为“cn-sg-robot-platform”、“cn-sg-capture-platform”、“cn-sg-easy-platform”、“cn-sg-content-platform”

数组$comparestrings具有值“sg-robot-platform”,“sg-easy-platform”

如果 $groupslist 中存在 $comparestring 值,我想打印一条消息(如果 cn-sg-robot-platform 中存在 sg-robot-platform,它应该打印一条消息)

我试过的代码没有执行模式搜索:(

$AdGroup = "cn-sg-robot-platform","cn-sg-capture-platform","cn-sg-easy-platform","cn-sg-content-platform"
$comparestrings = "sg-robot-platform" , "sg-easy-platform"

foreach ($item in $AdGroup) {
    $matchFound = $false
    foreach ($dev in $comparestrings) {
        if ($dev -like "*$item*") {
            $matchFound = $true
            echo "Match found"
            break
        }
    }
    if (-not $matchFound) {
        Write-Host "No match found for $item"
    }
}

**我想打印 sg-robot-platform 与 cn-sg-robot-platform 模式匹配时找到的匹配**

powershell oop wildcard
1个回答
1
投票

不太确定你打算在这里做什么,但如果你想输出可以找到匹配项的地方,这里有两种可能的解决方案:

  1. 遍历 $comparestrings 数组并测试每个值是否匹配
$groupslist     = "cn-sg-robot-platform","cn-sg-capture-platform","cn-sg-easy-platform","cn-sg-content-platform"
$comparestrings = "sg-robot-platform" , "sg-easy-platform"

foreach ($item in $comparestrings) {
    if ($groupslist -like "*$item*") {
        "Match found for $item"
    }
}
  1. 使用
    Where-Object
    并遍历结果
$groupslist     = "cn-sg-robot-platform","cn-sg-capture-platform","cn-sg-easy-platform","cn-sg-content-platform"
$comparestrings = "sg-robot-platform" , "sg-easy-platform"

$comparestrings | Where-Object { $groupslist -like "*$item*" } | ForEach-Object { "Match found for $_" }
# or use regex -match
# $comparestrings | Where-Object { $groupslist -match $item } | ForEach-Object { "Match found for $_" }

都会输出

Match found for sg-robot-platform
Match found for sg-easy-platform
© www.soinside.com 2019 - 2024. All rights reserved.