简体   繁体   English

如何匹配 PowerShell 中的字符串

[英]How to match a string in PowerShell

I'm trying to match a string in PowerShell, but I can't get True.我正在尝试匹配 PowerShell 中的字符串,但我无法获得 True。

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

Ok, maybe I gave too limited information of my problem.好的,也许我对我的问题提供的信息太有限了。

So here is a bit more information.所以这里有更多信息。 I have this code:我有这个代码:

$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

And the output value is empty for "Customer Support".并且“客户支持”的 output 值为空。

Here the space between "One" and "Two" will match literally "One Two".这里“一”和“二”之间的空格将与“一二”字面意思相匹配。 If you want to match any character between them use:如果要匹配它们之间的任何字符,请使用:

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

Here in Regex .在正则表达式中. means any character.表示任何字符。 Or you can append或者你可以 append

* = 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

I don't exactly understand what you are trying to achieve but you should take a look at PowerShell syntax and the -match operator.我不完全了解您要实现的目标,但您应该查看 PowerShell 语法和 -match 运算符。

Matching a role name like Customer Support is really just matching the same exact string when using regex.匹配像Customer Support这样的角色名称实际上只是在使用正则表达式时匹配相同的确切字符串。 One way to make this match like a wildcard would be使这种匹配通配符一样的一种方法是

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

This code is spliting any spaces in $String and combines them in a legit regex query "(Customer|Support)" .此代码拆分$String中的所有空格并将它们组合在合法的正则表达式查询"(Customer|Support)"中。

NOTE笔记

This code will match any string with the word "customer" and / or "support" in it.此代码将匹配其中包含“客户”和/或“支持”一词的任何字符串。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM