java 51 lines · 9 steps

Parsing user-agent strings with regex in Java

A compact parser pulls browser, version, and OS out of a raw user-agent string using precompiled patterns.

Explained by highlit
1public final class UserAgentParser {
2 
3 private static final Pattern OS_PATTERN = Pattern.compile(
4 "(Windows NT [0-9.]+|Mac OS X [0-9_]+|Android [0-9.]+|iPhone OS [0-9_]+|Linux)");
5 
6 private static final Pattern BROWSER_PATTERN = Pattern.compile(
7 "(Edg|OPR|Chrome|Firefox|Safari|MSIE|Trident)/?([0-9.]+)?");
8 
9 public record UserAgent(String browser, String version, String os) {}
10 
11 public UserAgent parse(String ua) {
12 if (ua == null || ua.isBlank()) {
13 return new UserAgent("Unknown", "", "Unknown");
14 }
15 return new UserAgent(browserName(ua), browserVersion(ua), operatingSystem(ua));
16 }
17 
18 private String browserName(String ua) {
19 Matcher m = BROWSER_PATTERN.matcher(ua);
20 String found = "Unknown";
21 while (m.find()) {
22 found = switch (m.group(1)) {
23 case "Edg" -> "Edge";
24 case "OPR" -> "Opera";
25 case "Trident", "MSIE" -> "Internet Explorer";
26 default -> m.group(1);
27 };
28 if (!found.equals("Safari")) {
29 return found;
30 }
31 }
32 return found;
33 }
34 
35 private String browserVersion(String ua) {
36 Matcher m = BROWSER_PATTERN.matcher(ua);
37 return m.find() && m.group(2) != null ? m.group(2) : "";
38 }
39 
40 private String operatingSystem(String ua) {
41 Matcher m = OS_PATTERN.matcher(ua);
42 if (!m.find()) {
43 return "Unknown";
44 }
45 String os = m.group(1).replace('_', '.');
46 if (os.startsWith("Windows NT")) return "Windows";
47 if (os.startsWith("Mac OS X")) return "macOS";
48 if (os.startsWith("iPhone OS")) return "iOS";
49 return os.split(" ")[0];
50 }
51}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Precompiling patterns as static finals avoids recompiling the regex on every call.
  2. 2User-agent parsing is inherently heuristic, so order and fallbacks matter more than a single perfect match.
  3. 3A record makes an immutable result object trivial to declare and return.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Parsing user-agent strings with regex in Java — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code