Match a RegEx to the same Group based on a conditional match of a string pattern- in Golang

Viewed 59

I have two test strings mp4/dach/zdf/22/07/220724_traumorte_italiens_romantische_inseln_inf/1/220724_traumorte_italiens_romantische_inseln_inf_508k_p9v15.mp4

and

/mp4/none/zdf/21/11/211124_1925_sendung_ban/1/211124_1925_sendung_ban_a3a4_508k_p9v15.mp4

I want a single RegEx to match the first string to get an output /dach/zdf/22/07/220724_traumorte_italiens_romantische_inseln_inf/1/220724_traumorte_italiens_romantische_inseln_inf

which I get with the RegEx ^.*[mp][4](.+)(?:a[0-9]a[0-9])?(?:.+_.+_.+_|_.+_).*$ or ^.*[mp][4](.+)(a[0-9]a[0-9]?(.+_.+_.+_)|(_.+_)).*$

but this matches the second string as /none/zdf/21/11/211124_1925_sendung_ban/1/211124_1925_sendung_ban_a3a4

but my expectation is to match 3 times _ if a3a4 is present; otherwise 2 times _ which should get the match /none/zdf/21/11/211124_1925_sendung_ban/1/211124_1925_sendung_ban for the second string.

But, somehow this is not grouping (Group -1) as intended.

Any pointers on this is appreciated.

Thanks!

1 Answers

You could use:

^\S*?\bmp4(/\S*?)(?:_a[0-9]a[0-9])?(?:_[^\s_]*){2}\.mp4$

Explanation

  • ^ Start of string
  • \S*?\bmp4 Match optional non whitespace chars, as least as possible, and them match mp4
  • ( Capture group 1
    • /\S*? Match / and match optional non whitespace chars, as least as possible
  • ) Close group 1
  • (?:_a[0-9]a[0-9])? Optionally match the pattern in the non capture group
  • (?:_[^\s_]*){2} Repeat 2 times _ and any char except _ and a whitespace char
  • \.mp4 Match .mp4
  • $ End of string

See a regex demo

Related