User-Agent strings are notorious for minor variations that make it hard to use them to categorize browsers, devices, and OS. The UA-Parser Core project maintains a giant Regex file that you can use to extract these elements.
The LUA Script found on the scripts page demonstrates the following techniques.