正则表达式以验证图像

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?

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")
    }
}

What you are looking for is the following (based off the example paths you posted):

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

Playground with examples

You can validate with the following Regex:

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

Ps: I made a flexible Regex, so it accepts a lot of formats of images: png, jpg, jpeg and so on..

You can test it here: Regex