404 regular-expression advice needed

It seems you can have both post ID’s and numbers in the page slug. So my-post-2 could be my-post with post ID 2 or my-post-2 with no post ID. In theory there is no way to solve this, but in practice maybe we can assume that you won’t have ten similar slugs, so the slug number is at most one digit, and the post ID is at least two digits. This way you can add the few posts with IDs 1-9 with a complete non-regex redirect.

This regex should match anything of the form /[year]/[month]/[optional-day]/[post-slug-with-optional single digit]-[optional post id][optional /]:

^/(\d{4})/\d{2}/(\d{2}/)?([^/]+?)(-\d{2,})?/?$

^/                                              Start of the string, one slash
  (\d{4})                                       Four digits, saved for later
         /                                      One slash
          \d{2}                                 Two digits, not saved
               /                                One slash
                (\d{2}/)?                       Two digits and a slash, optional
                         ([^/]+?)               Everything that is not a slash, but not greedy
                                 (-\d{2,})?     A dash and two or more digits, optional
                                           /?$  Optional slash and end of the string

The year is in the first captured group, the post slug in the third.

The “not greedy” is important because it makes sure that part of the regex doesn’t “eat up” the post-ID part that is matched after it. It is created by appending the ? to the +. I believe this does not work under Apache 1.3, so WordPress strips it out before it creates the mod_rewrite rules. So if it does not work when you put it in the Apache part of Redirection, try it in the WordPress part.

tech