Regular expression that if it matches the first group ignores the second group?

I have this regular expression:

isValidPath = regexp.MustCompile(`/user/action/?(.*)`)

It matches these 2 strings that are of interest to me:

"/user/action" and "/user/action/someResource"

But it also matches this other one:

"/user/actionblablablabla"

How do I make isValidPath not match this last one? It should only match these two paths:

"/user/action" and "/user/action/someResource"

Where someResource can be anything.

This works:

isValidPath = regexp.MustCompile(`/user/action$|/user/action/(.*)`)
1 Like

/user/action(/(.*))? and use match group 2 rather than 1 to extract the ressource.

This would still allow for /user/action/, if thats not wanted use .+ for the inner group instead.

Anyway, I do not thing that using a regex to validate this is a good thing, instead you probably want to use filepath.Match, as this generally also makes sure that the path is valid.

Your current regex (as well as my suggestion) would allow someRessource/someSubRessource, which might or might not be what you want. With the help of the mentionen function and those globs you could make it more explicit. You could as well with a regexp, but that again would make the regex more and more complicated.

Last but not least, Iā€™d probably use 2 seperate checks rather than one combined for equialtiy to the base path and being some resource path.

@NobbZ

someResource can be anything, all I want is a true or false, with your proposal I have to extract the path and then re-verify and that is not what I am looking for, I just want to know if the path meets that criteria and then pass the control to another package that will take care of the rest, I only need 1 regular expression for a particular case and it is not to validate thousands of paths as a router would do, so:

package main

import (
	"fmt"
	"regexp"
)

var rNum = regexp.MustCompile(`/user/action/(.*)|/user/action$`)

func main() {
	group := []string{
		"/user/action/",
		"/user/action/someresource/cat.png",
		"/user/action",
		"/user/actionblabla",
	}
	for _, urlPath := range group {
		fmt.Println(fmt.Sprintf("%s -> %t", urlPath, rNum.MatchString(urlPath)))
	}
}

With my regular expression:
var rNum = regexp.MustCompile(`/user/action/(.*)|/user/action$`)

Output:

/user/action/ -> true
/user/action/someresource/cat.png -> true
/user/action -> true
/user/actionblabla -> false

For now that is my solution.