使用RegEx匹配部分字符串内容?

时间:2020-09-20 13:04:59

标签: regex powershell

在创建正则表达式以匹配这些内置组时,我需要一些帮助:

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

2 个答案:

答案 0 :(得分:2)

为什么不对样式进行略微修改的选择字符串呢?

'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
#>

答案 1 :(得分:1)

您需要构建如下模式:

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

它将导致

PS> $reExcludeObjects
^(?:Enterprise|Admins|Organization|Exchange)(\s[a-z-]+){1,3}$

因此,重点是要为{0}字符串使用-f占位符,并为文字括号使用双括号。