One way to count the number of artists is to write a list with a unique separator between each artist and then use the length of the resulting string and the length of the same string when the separator is removed by replacing it with nothing.
So if we use { to separate artists when creating ListOfArtists, the following code creates a variable called NumberOfArtists:
$puts(NumberOfArtists,$add($sub($len($get(ListOfArtists)),$len($replace($get(ListOfArtists),{,))),1))
Then this code will write the artist list as you want:
$if($grtr($get(NumberOfArtists),5),Various Artists,$replace($get(ListOfArtists),{,',' ))
I'm not sure of the final product you want but your existing code produces many blank lines that seem unnecessary.
Every line of code in the MTE file creates one line in the exported result.
And I'm puzzled by your use of regex since I provided a simpler alternative.
There is no need to use regex to remove duplicate artists if you use $loop(%artist%,1)
Anyhow, here's my solution:
$loop(%album%,1)$loop(%artist%,1)$puts(ListOfArtists,$get(ListOfArtists){%artist%)$loopend()$puts(ListOfArtists,$cutLeft($get(ListOfArtists),1))
ALBUM: %album%
ARTIST: $puts(NumberOfArtists,$add($sub($len($get(ListOfArtists)),$len($replace($get(ListOfArtists),{,))),1))$if($grtr($get(NumberOfArtists),5),Various Artists,$replace($get(ListOfArtists),{,',' ))$puts(ListOfArtists,)$loopend()