Make removal of failed mechanism safer

(Removing a space before and after would join the preceding and following
mechanisms together. Also, escape any regexp metacharacters.)
Exit loop over AUTH mechanisms when there are no more left to avoid infinite loop
Note changes for commit fdcacd730e