【问题标题】:How to match a string in PowerShell如何在 PowerShell 中匹配字符串
【发布时间】:2020-12-04 03:11:57
【问题描述】:

我正在尝试在 PowerShell 中匹配一个字符串,但我无法获得 True。

"one.two" -match "One Two"
False

好吧,也许我对我的问题提供的信息太有限了。

所以这里有更多信息。我有这个代码:

$userRoles = @('User', 'Customer Support');
$adGroups = @('ad.group.user', 'ad.group.customer.admin');
$userRoleToAdGroup = @{};
foreach ($userRole in $userRoles) {
    $adGroupsMatch = @($adGroups -match "$userRole")
    $userRoleToAdGroup.Add($userRole, $adGroupsMatch)
}
$userRoleToAdGroup

“客户支持”的输出值为空。

【问题讨论】:

  • 从你提供的有限信息来看,我猜你的字符串是错误的。试试:"One Two" -match "one.two"。要测试的字符串应该出现在左边,而正则表达式模式应该出现在右边。
  • 我将问题缩小到非常简单的匹配。是的,绕过它的方法有效,但在这种情况下不起作用:“here.is.some.text”-match“Some Text”。
  • 正如@boxdog 试图解释的那样,用于测试 with 的正则表达式模式应该位于-match 运算符的右侧。您评论的示例使用了一个根本不是正则表达式模式的文字字符串(带空格)。
  • 标题太笼统了。因此,对于 “PowerShell 模糊字符串匹配” 之类的查询,此问题会出现在搜索引擎结果中。一个更规范的问题是:PowerShell and the -contains operator(答案涵盖了-Contains(用于集合)、-match/-imatch(正则表达式字符串匹配)和-like之间的区别, -ilike(类似 SQL 的匹配))

标签: string powershell match


【解决方案1】:

这里“一”和“二”之间的空格将匹配字面上的“一二”。如果要匹配它们之间的任何字符,请使用:

"one.two" -match "One.Two"

在正则表达式中,. 表示任何字符。或者你可以追加

* = 0 or more instances of previous charcter
+ = 1 or more instances of previous charcter
? = 0 or 1 instances of previous charcter
\w = match any word
\d = match any digit
\s = match any whitespace
{n,m} = match n to m instances of previous charcter

【讨论】:

    【解决方案2】:

    我不完全理解您想要实现的目标,但您应该看看 PowerShell 语法和 -match 运算符。

    匹配Customer Support 之类的角色名称实际上只是在使用正则表达式时匹配相同的确切字符串。使这种匹配通配符的一种方法是

    $String = "Customer Support"
    $MatchString = "($($String -replace '\s+', '|'))"
    'ad.group.customer.admin' -match $MatchString
    True
    

    此代码拆分$String 中的所有空格,并将它们组合到一个合法的正则表达式查询"(Customer|Support)"

    注意

    此代码将匹配其中包含“客户”和/或“支持”一词的任何字符串。

    'ad.group.user.support' -match $MatchString
    True
    

    【讨论】:

    • 谢谢,这正是我需要的。
    猜你喜欢
    • 2018-12-26
    • 2018-04-25
    • 1970-01-01
    • 2011-10-31
    • 1970-01-01
    • 2016-11-11
    • 1970-01-01
    • 1970-01-01
    • 2015-01-25
    相关资源
    最近更新 更多