1.8:
string.gsub(/(\A|[^A])B/, '\1_B')

1.9:
string.gsub(/(?<!A)B/, '_B')