考虑以下正则表达式的 powershell 示例。此正则表达式满足您的示例,但是它确实使用了一些 python 可能不允许的外观。
(?<!Chrome.*?)Safari(?!.*?Chrome)|(?<!Safari.*?)Chrome(?!.*?Safari)|(?<!(Chrome|Safari).*?)$
demo'd here as Output 1. 仅当chrome
或safari
在同一字符串上时才会失败
(?<!Chrome.*?)Safari|(?<!Safari.*?)$
demo'd here as Output 2. 仅当chrome
后面跟着safari
例子
$Matches = @()
[array]$input = @()
$input += 'Chrome Mobile/12345 Safari'
$input += 'Like MAC OS Safari'
$input += 'Safari Mobile/12345 Chrome'
$input += 'Like MAC OS chrome'
$input += 'Internet Explorer is deprecated'
$input += 'I like Chrome better then Safari for looking at kittens'
$input += 'Safari is easier to vote with'
$Regex = '(?<!Chrome.*?)Safari(?!.*?Chrome)|(?<!Safari.*?)Chrome(?!.*?Safari)|(?<!(Chrome|Safari).*?)$'
Write-Host Output 1
foreach ($String in $Input) {
if ( $String -imatch $Regex ) {
write "'$String' `t matched"
} else {
write "'$String' `t did not match"
} # end if
} # next
Write-Host
Write-Host Output 2
# but I want to allow for only:
# match any text without the word "Chrome" followed by the word "Safari"
$Regex = '(?<!Chrome.*?)Safari|(?<!Safari.*?)$'
foreach ($String in $Input) {
if ( $String -imatch $Regex ) {
write "'$String' `t matched"
} else {
write "'$String' `t did not match"
} # end if
} # next
产量
Output 1
'Chrome Mobile/12345 Safari' did not match
'Like MAC OS Safari' matched
'Safari Mobile/12345 Chrome' did not match
'Like MAC OS chrome' matched
'Internet Explorer is deprecated' matched
'I like Chrome better then Safari for looking at kittens' did not match
'Safari is easier to vote with' matched
Output 2
'Chrome Mobile/12345 Safari' did not match
'Like MAC OS Safari' matched
'Safari Mobile/12345 Chrome' matched
'Like MAC OS chrome' matched
'Internet Explorer is deprecated' matched
'I like Chrome better then Safari for looking at kittens' did not match
'Safari is easier to vote with' matched
概括