Pattern Match

Welcome Forums General PowerShell Q&A Pattern Match

This topic contains 4 replies, has 3 voices, and was last updated by

5 years ago.

  • Author
  • #11667

    Points: 0
    Rank: Member

    I am trying to create a script that will detect pattern matches. I subbed some things from an old script. But I must be forgetting something. This script is suppose to match the pattern in a SS number and display the message... "you got it correct" or Please try again. The info I am missing has to be something simple...I just don't see it. Any help any one can provide would be appreciated. Thanks

    $mynumbers = "[0-9]{3}-[0-9]{2}-[0-9]{4}"
    $question1 =""

    write-host "nnnnnn`n
    "Press enter to Continue:""
    while ($question1 -ne $mynumbers){
    Write-Host "Do you know the format of your SS Number ?"
    $question1 = Read-Host "Please enter your SS Number and Press the enter key"

    if ($question1 -eq $mynumbers){
    write-host " You know your formats"}
    if ($question1 -ne $mynumbers){
    write-host "Please try again"}

  • #11668

    Points: 1,704
    Helping HandTeam Member
    Rank: Community Hero

    Sorry, the forums software doesn't take kindly to back ticks. You might want to revise your code listing.

    The problem is that you're using the -ne operator, which means "not EXACTLY equal to" and -eq, which means "EXACTLY equal to." You probably want to look at the -match and -notmatch operators instead, which work with regular expressions.

  • #11669

    Points: 0
    Rank: Member

    Hi Don,
    I'll give that a try and see what happens. I bet your right though.
    Thank you for the help.

  • #11670

    Points: 0
    Rank: Member

    That should have been "you're". I hate it when I do that. I still had to change a few things other than match and not match...but it works.
    Thanks again

  • #11703

    Points: 0
    Rank: Member

    You may want to use the digits class rather than explicitly defining a range.

    $pattern = [regex]"\d{3}-?\d{2}-?\d{4}"
    $input = Read-Host "Enter your SSAN"
    $input -match $pattern

    The question mark in the regex allows you to omit the dash. If you require the dash, remove the question marks.

The topic ‘Pattern Match’ is closed to new replies.