Fix gsub errors. Fix #1734

Huge thanks to @campadrenalin who finally figured out the bug.