sourcetip

Powershell: match 연산자가 true를 반환하지만 $matches가 null입니다.

fileupload 2023. 8. 16. 22:33
반응형

Powershell: match 연산자가 true를 반환하지만 $matches가 null입니다.

파일 내용을 일치시키기 위해 정규식으로 작업하고 있습니다.

> (get-content $_) -match $somePattern
the line of text that matches the pattern

true를 반환합니다. 일치하지만 $165 변수는 null로 유지됩니다.

> $matches -eq $null
True

$matches에 매치 그룹이 있어야 하지 않나요?

엄밀히 말하면string -match ...그리고.collection -match ...서로 다른 두 연산자입니다.첫 번째 값은 부울 값을 얻고 다음 값을 채웁니다.$matches두 번째는 패턴과 일치하지만 채우기가 아닌 것으로 보이는 각 컬렉션 항목을 가져옵니다.$matches.

파일에 한 줄이 포함된 경우(첫 번째 연산자가 작동함) 예제는 예상대로 작동해야 합니다.파일에 2개 이상의 행이 포함되어 있으면 두 번째 연산자가 사용되고,$matches설정되지 않았습니다.

컬렉션에 적용된 다른 부울 연산자도 마찬가지입니다.그것은collection -op ...항목 반환 위치item -op ...사실입니다.

예:

1..10 -gt 5 # 6 7 8 9 10
'apple', 'banana', 'orange' -match 'e' # apple, orange 

컬렉션에 적용된 부울 연산자는 올바르게 사용할 경우 유용합니다.하지만 그것들은 또한 혼란스러울 수 있고 실수하기 쉬운 것으로 이어질 수 있습니다.

$object = @(1, $null, 2, $null)

# "not safe" comparison with $null, perhaps a mistake
if ($object -eq $null) {
    '-eq gets @($null, $null) which is evaluated to $true by if!'
}

# safe comparison with $null
if ($null -eq $object) {
    'this is not called'
}

를 사용한 다른 예-match그리고.-notmatch혼란스러워 보일 수 있음:

$object = 'apple', 'banana', 'orange'

if ($object -match 'e') {
    'this is called'
}

if ($object -notmatch 'e') {
    'this is also called, because "banana" is evaluated to $true by if!'
}

저도 같은 문제가 있었고, 정확한 행은 Powershell 명령 프롬프트에서 작동했지만 Powershell ISE나 일반 명령 프롬프트에서는 작동하지 않았습니다.파일의 모든 줄을 각각을 사용하여 하나씩 순환하지 않으려면 다음과 같은 문자열로 변환하면 됩니다.

if([string](Get-Content -path $filePath) -match $pattern)
{
   $matches[1]
}

언급URL : https://stackoverflow.com/questions/8651905/powershell-match-operator-returns-true-but-matches-is-null

반응형