Trimming lastSegment from a URI trims that PLUS the last number of the previous segment
Twig's |trim filter is just a wrapper for PHP's trim() method, which says:


  Strip whitespace (or other characters) from the beginning and end of a string


So in your example, you're telling it to strip all / and 2 from the beginning and end of the given string, which explains the output you're seeing.

I think you'll be better off by installing something like the Twig PCRE plugin, which gives Twig full access to the PHP preg_ regex methods.

Then you'd just do a preg_match to target exactly what you're looking for and replacing it with new values as necessary.