dongtigai3875 2019-08-10 19:02
浏览 102
已采纳

IPv4正则表达式捕获地址的不正确部分

This question already has an answer here:

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!

</div>
  • 写回答

2条回答 默认 最新

  • duanci3845 2019-08-10 19:20
    关注

    Maybe, this expression might be closer to what you might have in mind:

    ^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$
    

    Test

    package main
    
    import (
        "regexp"
        "fmt"
    )
    
    func main() {
        var re = regexp.MustCompile(`(?m)^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$`)
        var str = `127.0.0.1
    192.168.1.1
    192.168.1.255
    255.255.255.255
    0.0.0.0
    1.1.1.01
    
    30.168.1.255.1
    127.1
    192.168.1.256
    -1.2.3.4
    3...3`
    
        for i, match := range re.FindAllString(str, -1) {
            fmt.Println(match, "found at index", i)
        }
    }
    

    The expression is explained on the top right panel of regex101.com, if you wish to explore/simplify/modify it, and in this link, you can watch how it would match against some sample inputs, if you like.

    Reference:

    Validating IPv4 addresses with regexp

    RegEx Circuit

    jex.im visualizes regular expressions:

    enter image description here

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法