PowerShell REGEX quandry

Roger Zimmerman 1 Reputation point
2021-06-07T20:05:12.57+00:00

I'm totally lost on this regex result on PowerShell.
PS C:\Windows\system32> "917021" -match "[0-9]{4}"
True
Also tried this:
PS C:\Windows\system32> "917021" -match "[0-9]{4,5}"
True
According to all the rules in the book, this should limit the string to four characters and in the second case to five characters at the most. In fact, as I read it this is the very reason for the curly braces. Yet PowerShell passes both versions. Can anyone explain this behavior?

Windows for business | Windows Server | User experience | PowerShell
{count} votes

4 answers

Sort by: Most helpful
  1. MotoX80 37,156 Reputation points
    2021-06-08T00:50:59.63+00:00

    You just need to examine the $matches variable. Or $matches[0].

    103202-capture.jpg

    0 comments No comments

  2. Roger Zimmerman 1 Reputation point
    2021-06-08T01:26:50.433+00:00

    That makes some sense to me, except it seems deceptive that it would return a TRUE if it isn't a complete match, when the whole point of the { } is to limit the set of characters to only 4 (or 5). It seems that the whole point of regex is to filter out mismatches. Let's say I wanted to only send something to servers named 9070 and 90702, but not 907024 and 907025. The script sees that the partial match and returns TRUE, defeating the point of the { }. Doesn't that seem wrong somehow? Forgive me if I'm being a bit dense on this.


  3. Anonymous
    2021-06-08T01:46:51.507+00:00

    Hi,

    [0-9]{4} matches 9170 and [0-9]{4,5} matches 91702 so they both return TRUE. To retrieve captured text you could use the $Matches hashtable automatic variable

    103203-image.png

    Best Regards,
    Ian Xue

    ============================================

    If the Answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  4. Roger Zimmerman 1 Reputation point
    2021-06-08T03:38:46.67+00:00

    Thanks all for your input. This is going to take some work, I can see. i am thankful to the community for your patience and help.

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.