You can use the expression right(text,2) to get the two right most characters. You can use a dictionary to reference into an array based on those characters.
Read in your words, get the right most characters. Check for that dictionary entry. If is exists, pick the array by UID, push the word onto the array. If it doesn't exist, create a new array, add the entry to the dictionary with the array UID, push the entry onto the array.
Now you just need to grab the last two characters from the input, see if that entry exists in the dictionary, if it does, pick the array by UID, and grab some entry from the array.