I’m not sure if you can do this via .htaccess, but you can probably do this with code. For instance, in PHP, you can first collect the URL and use that as a variable to parse with whatever logic you need and then set the header to that new page with a 301.
You can actually use .htaccess to force all requests into a main
index.php file that will handle the requests. Almost like a front-controller.