Pattern Match

This topic contains 4 replies, has 3 voices, and was last updated by  Bob McCoy 4 years ago.

  • Author
    Posts
  • #11667

    Michael Coffey
    Participant

    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:""
    Read-host
    while ($question1 -ne $mynumbers){
    Write-Host "Do you know the format of your SS Number ?"
    write-host
    write-host
    write-host
    $question1 = Read-Host "Please enter your SS Number and Press the enter key"
    }
    read-host

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

  • #11668

    Don Jones
    Keymaster

    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

    Michael Coffey
    Participant

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

  • #11670

    Michael Coffey
    Participant

    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

    Bob McCoy
    Participant

    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.

You must be logged in to reply to this topic.