regex alternate select wrong match

Viewed 55

I have names like this :

\\SRV\Share\TVS\My Super Tv Show\Season 11\S11E12 - some title.jpg
\\SRV\Share\TVS\My Super Tv Show\Season 11\12-sometitle.png
\\SRV\Share\TVS\My Super Tv Show\S11E12 -some title.fdf
\\SRV\Share\TVS\My Super Tv Show\Season 11-E12 - Some title.fdgfg
\\SRV\Share\TVS\My Super Tv Show\Season 11 Ep12 - Some Title.jpeg
\\SRV\Share\TVS\My Super Tv Show\11x12 - Some Title.jpeg

I need to retrieve My Super Tv Show, season number and episode number.

I tried many regex, last is :

.+\\.+\\(?<TvShow>.+?)[. -\\]+?((Season (?<Season>\d+)\\[sS]\d+[eE])|([sS](eason )?(?<Season>\d+)[. -]*[eE]?p?[. -\\]*)|((?<Season>\d+)[xX]))(?<Episode>\d+)

it does not recover the tv show name from the first name, and gets only 2 instead of 12 for episode number (except for the last name)

Any help would be greatly appreciate :)

2 Answers

You might also use 3 named capture groups without the alternations

\\(?<TvShow>[^\\]+)\\(?:S(?:eason)?\s*)?(?<Season>\d+)[\\Ex -](?:S\d+E|Ep?)?(?<Episode>\d+)

The pattern matches

  • \\ Match \
  • (?<TvShow>[^\\]+) Capture any char except \
  • \\(?:S(?:eason)?\s*)? Optionally match variations of Season
  • (?<Season>\d+) Capture 1+ digits
  • [\\Ex -] Match 1 of the listed chars
  • (?:S\d+E|Ep?)? Optionally match SE and 1+ digits or E with optional p
  • (?<Episode>\d+) Capture 1+ digits

Regex demo

enter image description here

See a .NET regex demo

You can use

^\\\\(?:[^\\]+\\){3}(?<TvShow>[^\\]+)\\(?:Season\s*(?<Season>\d+)\\(?:(?<Episode>\d+)|S\d+E(?<Episode>\d+))|Season\s*(?<Season>\d+)[\s-]*Ep?(?<Episode>\d+)|S(?<Season>\d+)E(?<Episode>\d+)|(?<Season>\d+)x(?<Episode>\d+))

See the regex demo

enter image description here

Details:

  • ^ - start of string
  • \\\\ - a \\ string
  • (?:[^\\]+\\){3} - three occurrences of one or more chars other than \ and then a \
  • (?<TvShow>[^\\]+) - Group "TvShow": one or more chars other than \
  • \\ - a \ char
  • (?: - start of a non-capturing groups:
    • Season\s*(?<Season>\d+)\\(?:(?<Episode>\d+)|S\d+E(?<Episode>\d+)) - Season, 0+ whitespaces, one or more digits ("Season" group), \, then either one or more digits ("Episode" group) or S, one or more digits, E, one or more digits ("Episode" group)
    • | - or
    • Season\s*(?<Season>\d+)[\s-]*Ep?(?<Episode>\d+) - Season, zero or more whitespaces, one or more digits ("Season" group), zero or more whitespace/hyphens, E, an optional p, one or more digits ("Episode" group)
    • | - or
    • S(?<Season>\d+)E(?<Episode>\d+) - S, one or more digits ("Season" group), E, one or more digits ("Episode" group)
    • | - or
    • (?<Season>\d+)x(?<Episode>\d+) -one or more digits ("Season" group), x, one or more digits ("Episode" group)
  • ) - end of the group.
Related