I'm trying to write a program that prints the invalid part or parts of an IPv4 address from terminal input.
Here is my code:
package chapter4
import (
"bufio"
"fmt"
"os"
"regexp"
"strings"
"time"
)
func IPV4() {
var f *os.File
f = os.Stdin
defer f.Close()
scanner := bufio.NewScanner(f)
fmt.Println("Exercise 1, Chapter 4 - Detecting incorrect parts of IPv4 Addresses, enter an address!")
for scanner.Scan() {
if scanner.Text() == "STOP" {
fmt.Println("Initializing Level 4...")
time.Sleep(5 * time.Second)
break
}
expression := "(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])"
matchMe, err := regexp.Compile(expression)
if err != nil {
fmt.Println("Could not compile!", err)
}
s := strings.Split(scanner.Text(), ".")
for _, value := range s {
fmt.Println(value)
str := matchMe.FindString(value)
if len(str) == 0 {
fmt.Println(value)
}
}
}
}
My thought process is that for every terminal IP address input, I split the string by '.'
Then I iterate over the resulting []string
and match each value to the regular expression.
For some reason the only case where the regex expression doesn't match is when there are letter characters in the input. Every number, no matter the size or composition, is a valid match for my expression.
I'm hoping you can help me identify the problem, and if there's a better way to do it, I'm all ears. Thanks!