0

I use if else in my powershell script.

if ($match.Groups.Count) {
    while ($match.Success) {
        Write-Host ("Match found: {0}" -f $match.Value)
        $match = $match.NextMatch()
    }
}
else {

    Write-Host "Not Found"
}

in the if side, it works, but in the else side, It cannot return "Not Found" . It does not show any error.

2
  • 1
    If I try to simulate this code by guessing what I think $match contains, the code works for me. If you ever enter that if block, you are never going to enter the else block no matter how many times you use .NextMatch() without a loop outside of the if/else or calling this entire code block again separately. If the goal is to assign $match somewhere above and expect an output of "Match found: , Match found: ....Not found," it can't happen without entering that code block again on another iteration. Commented Mar 11, 2019 at 2:57
  • 1
    Even failed match have at least one group: [regex]::Match('a', 'b').Groups.Count. Commented Mar 11, 2019 at 3:30

1 Answer 1

3

PetSerAl, as countless times before, has provided the crucial pointer in a comment:

Perhaps surprisingly, the [System.Text.RegularExpressions.Match] instance returned by the static [regex]::Match() method (or its instance-method counterpart) contains 1 element in its .Groups property even if the matching operation didn't succeed[1], so that, assuming an instance stored in $match, $match.Groups.Count always returns $true.

Instead, use the .Success property to determine if a match was found, as you already do in the while loop:

if ($match.Success) {
    while ($match.Success) {
        "Match found: {0}" -f $match.Value
        $match = $match.NextMatch()
    }
} else {
    "Not Found"
}

Note that I've removed the Write-Host calls, because Write-Host is generally the wrong tool to use, unless the intent is explicitly to write to the display only, thereby bypassing PowerShell's output streams and thus the ability to send the output to other commands, capture it in a variable or redirect it to a file.


[1] [regex]::Match('a', 'b').Groups.Count returns 1, even though the match clearly didn't succeed.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.