duanmajing9332 2016-02-28 20:25
浏览 48
已采纳

正则表达式以验证图像

I am writing a web application in golang. I am using regular expression to validate the URL. But I am not able to validate image (abc.png) in the URL validation.

var validPath = regexp.MustCompile("^/$|/(home|about|badge)/(|[a-zA-Z0-9]+)$")

The above URL takes /home/, /about/ but could not make for /abc.png. I mean . itself not working

I tried the following regex, but it didn't help

var validPath = regexp.MustCompile("^/$|/(home|about|badge|.)/(|[a-zA-Z0-9]+)$")
var validPath = regexp.MustCompile("^/$|/(home|about|badge)(/|.)(|[a-zA-Z0-9]+)$")

And I am trying to match http://localhost:8080/badge.png

Could anyone please help me on this?

  • 写回答

3条回答 默认 最新

  • douchui7332 2016-03-02 20:41
    关注

    It appears

    ^/$|^(?:/(home|about|badge))?/((?:badge|abc)\.png|[a-zA-Z0-9]*)$
    

    should work for you. See the regex demo.

    The pattern breakdown:

    • ^/$ - a / as a whole string
    • | - or...
    • ^ - start of string
    • (?:/(home|about|badge))? - optional sequence of / + either home, or about or badge
    • / - a / symbol followed with
    • ((?:badge|abc)\.png|[a-zA-Z0-9]*) - Group 1 capturing:
      • (?:badge|abc)\.png - badge or abc followed with .png
      • | - or...
      • [a-zA-Z0-9]* - zero or more alphanumerics
    • $ - end of string

    And here is the Go playground demo.

    package main
    
    import "fmt"
    import "regexp"
    
    func main() {
        //var validPath = regexp.MustCompile("^/((home|about)(/[a-zA-Z0-9]*)?|[a-zA-Z0-9]+\\.[a-z]+)?$")
        var validPath = regexp.MustCompile(`^/$|^(?:/(home|about|badge))?/((?:badge|abc)\.png|[a-zA-Z0-9]*)$`)
    
        fmt.Println(validPath.MatchString("/"), validPath.MatchString("/home/"), validPath.MatchString("/about/"), validPath.MatchString("/home/13jia0"), validPath.MatchString("/about/1jnmjan"), validPath.MatchString("/badge.png"), validPath.MatchString("/abc.png"))
        fmt.Println(validPath.MatchString("/nope/"), validPath.MatchString("/invalid.png"), validPath.MatchString("/test/test"))
    
        m := validPath.FindStringSubmatch("/about/global")
        fmt.Println("validate() :: URL validation path m[1] : ", m[1])
        fmt.Println("validate() :: URL validation path m[2] : ", m[2])
        if m == nil || m[2] != "global" {
            fmt.Println("Not valid")
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥200 基于同花顺supermind的量化策略脚本编辑
  • ¥20 Html备忘录页面制作
  • ¥15 黄永刚的晶体塑性子程序中输入的材料参数里的晶体取向参数是什么形式的?
  • ¥20 数学建模来解决我这个问题
  • ¥15 计算机网络ip分片偏移量计算头部是-20还是-40呀
  • ¥15 stc15f2k60s2单片机关于流水灯,时钟,定时器,矩阵键盘等方面的综合问题
  • ¥15 YOLOv8已有一个初步的检测模型,想利用这个模型对新的图片进行自动标注,生成labellmg可以识别的数据,再手动修改。如何操作?
  • ¥30 NIRfast软件使用指导
  • ¥20 matlab仿真问题,求功率谱密度
  • ¥15 求micropython modbus-RTU 从机的代码或库?