首页 > 解决方案 > 使用 RegEx 匹配部分字符串内容?

问题描述

在创建 RegEx 以匹配这些内置组时,我需要一些帮助:

Domain Admins
Enterprise Admins
Exchange All Hosted Organizations
Exchange Domain Servers
Exchange Enterprise Servers
Exchange Install Domain Servers
Exchange Organization Administrators
Exchange Public Folder Administrators
Exchange Recipient Administrators
Exchange Servers
Exchange Trusted Subsystem
Exchange View-Only Administrators
Exchange Windows Permissions
Recipient Management
Organization Management

我尝试了以下匹配模式,但它给了我一些错误:

$groups_to_ignore = ('Enterprise', 'Admins', 'Organization', 'Exchange')
$reExcludeObjects = '^(\s[a-z-]+){1,3}$' -f (($groups_to_ignore | ForEach-Object { [regex]::Escape($_) }) -join '|')
$reExcludeObjects

错误代码:

Error formatting a string: Index (zero based) must be greater than or equal to zero and less than the size of the argument list..
At line:2 char:1
+ $reExcludeObjects = '^(\s[a-z-]+){1,3}$' -f (($groups_to_ignore | For ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (^(\s[a-z-]+){1,3}$:String) [], RuntimeException
    + FullyQualifiedErrorId : FormatError

这是预览:https ://regex101.com/r/WKal3Y/1

标签: regexpowershell

解决方案


为什么不直接使用 Select-String 对您的模式稍作修改呢?

'Domain Admins
Enterprise Admins
Exchange All Hosted Organizations
Exchange Domain Servers
Exchange Enterprise Servers
Exchange Install Domain Servers
Exchange Organization Administrators
Exchange Public Folder Administrators
Exchange Recipient Administrators
Exchange Servers
Exchange Trusted Subsystem
Exchange View-Only Administrators
Exchange Windows Permissions
Recipient Management
Organization Management
' | Out-File -FilePath 'D:\Temp\BuiltInGroups.txt'

Clear-Host
Get-Content -Path 'D:\Temp\BuiltInGroups.txt' | 
ForEach-Object {$PSItem | Select-String -Pattern '^((?!Enterprise|Organization|Exchange).)*$'}
# Results
<#
Domain Admins
Recipient Management
#>

推荐阅读