我正在尝试使用正则表达式在Powershell中编写where子句,该正则表达式仅匹配不以[AND不以]结尾的行(数组中的项)(ini头)。
$test = @('test', '[test]', '[te]st', 'te[st]')
以下是我所能得到的。它仅匹配“测试”。
$test | where-object {$_ -match '^(?!\[).+(?<!\])$'}
“ test”,“ [te] st”和“ te [st]”应匹配。谢谢。
问题
在中[te]st
,初始负前瞻失败。
在中te[st]
,最后的否定后向失败。
解
我们需要使用交流发电机|
来确保一种或另一种情况都有效。如果两种环视均失败,那么我们将不会获得匹配:
^ (?# match the beginning of the string)
(?: (?# start non-capturing group)
(?!\[) (?# negative lookahead for [)
.+ (?# match 1+ characters)
| (?# OR)
.+ (?# match 1+ characters)
(?<!\]) (?# negative lookbehind for ])
) (?# end non-capturing group)
$ (?# match the end of the string)
注:我把轮换到非捕获组,这样我就不需要包括锚^
和$
周围的每一个可能的声明。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句