How to add an if condition to regex on Golang to match only if the group exists in Golang

Viewed 39

I am testing two strings and want a common regex to be applied based on the condition if one group exists then apply the Regex Pattern, else other Pattern, but some reason on Regex online editor it seems that the ?=() is not recognized to add if else condition.

I have the following 2 test strings:

/public/weltweit/nfsk/2022/05/18/668e9f57-30be-40b6-bc85-5bf66671e41d/668e9f57-30be-40b6-bc85-5bf66671e41d_AVC-270.mp4

Expected extraction using ^\/(\bpublic\b[\/])*(.+[a-z]{1,}.*[\/|_]+)+.*?$ is

weltweit/nfsk/2022/05/18/668e9f57-30be-40b6-bc85-5bf66671e41d/668e9f57-30be-40b6-bc85-5bf66671e41d_

which is expected but for the other test string :

/medp/ondemand/weltweit/fsk0/258/2580407/2580407_40256616.mp4 with same Regex I get medp/ondemand/weltweit/fsk0/258/2580407/2580407_

My expected extraction is **medp/ondemand/weltweit/fsk0/258/2580407/** I want to add a if condition to a group (\bpublic\b[\/]) so that an underscore **_**is chosen if the group exists; otherwise a slash **/**

Any pointers is appreciated.

Thank you!

1 Answers

You can use

^/(?:public/(.*_)|(.*/))

See the regex demo. The result is either in Group 1 or Group 2.

Details:

  • ^ - start of string
  • / - a slash
  • (?: - start of a non-capturing group:
    • public/ - a fixed string
    • (.*_) - Group 1: any zero or more chars other than line break chars as many as possible and then a _ char
    • | - or
    • (.*/) - Group 2: any zero or more chars other than line break chars as many as possible and then a / char
  • ) - end of the group.
Related