Hi, what's the language your existing script was written in?
Preferrably Python or Scheme (i.e. Script-Fu). I can understand the two langugages in minutes, and then develop further to meet your need.
Here's another question, what do you mean by X1, X2, X3?
Are you referring to names that share a same stem, but with different numeric suffixes?
For instance., 'Layer1', 'Layer2' and so on. Y1, Y2, Y3 should also be the same case, e.g., 'YetAnotherLayer1', 'YetAnotherLayer2'.
Therefore these two groups of layers to be combined can be easily differentiated in scripts. Alternatively, it's also fine if they are already grouped in GIMP.