Hmm, you could do it with regular expressions, but this is probably not the most practical way.

I would read the file and load the data into an appropriate data structure, probably a hash of arrays (HoA), where the keys would be the group names and the values arrays of users. Then do all the changes that need to be done on this HoA, and, once the changes are completed, write back the data to the file.

A quick example at the command line, just to give you an idea on how to do it and of the resulting data structure: