Wanindu Hasaranga became only the third player in T20 World Cup history to bag a hat-trick, joining Brett Lee and Curtis Campher.
David Miller scored an unbeaten 23 off 13 deliveries, smashing two humongous maximums in the final over to turn the tide of the match.
The Sri Lanka batters looked well set to launch from a strong foundation, but Tabraiz Shamsi and Dwaine Pretorius helped South Africa pull things back.