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