Saturday, June 22, 2024
HomeGolangCommon expression that if it matches the primary group ignores the second...

Common expression that if it matches the primary group ignores the second group? – Getting Assist


I’ve this common expression:

isValidPath = regexp.MustCompile(`/consumer/motion/?(.*)`)

It matches these 2 strings which can be of curiosity to me:

"/consumer/motion" and "/consumer/motion/someResource"

But it surely additionally matches this different one:

"/consumer/actionblablablabla"

How do I make isValidPath not match this final one? It ought to solely match these two paths:

"/consumer/motion" and "/consumer/motion/someResource"

The place someResource might be something.

This works:

isValidPath = regexp.MustCompile(`/consumer/motion$|/consumer/motion/(.*)`)



1 Like

/consumer/motion(/(.*))? and use match group 2 slightly than 1 to extract the ressource.

This could nonetheless enable for /consumer/motion/, if thats not wished use .+ for the internal group as an alternative.

Anyway, I don’t factor that utilizing a regex to validate it is a good factor, as an alternative you most likely wish to use filepath.Match, as this usually additionally makes certain that the trail is legitimate.

Your present regex (in addition to my suggestion) would enable someRessource/someSubRessource, which could or won’t be what you need. With the assistance of the mentionen perform and people globs you could possibly make it extra express. You might as effectively with a regexp, however that once more would make the regex increasingly sophisticated.

Final however not least, I’d most likely use 2 seperate checks slightly than one mixed for equialtiy to the bottom path and being some useful resource path.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments