正则表达式提取设备型号问题:修复User-Agent匹配异常
Fixing User-Agent Model Extraction Regex
The issue with your current regex .*?\(.*;(?<model>.*?)(; wv)?\) is that the lazy .*? matcher prioritizes the shortest possible match when it hits the optional (; wv)? group. For your third User-Agent example, this causes it to capture "wv" instead of the intended model string. Let's adjust the regex to explicitly handle both scenarios (with and without ; wv at the end of the parenthetical content):
Corrected Regex
.*?\(.*?(?:;(?<model>[^;]+); wv|;(?<model>[^;]+))\)
Regex Breakdown
This pattern aligns perfectly with your extraction rules:
.*?\(: Non-greedily matches up to the opening parenthesis of the first(...)section..*?: Non-greedily matches content inside the parentheses until we hit one of two target patterns.(?:...): A non-capturing group that handles both cases:;(?<model>[^;]+); wv: For entries ending with; wv, this captures all characters (no internal semicolons) between the penultimate semicolon and the; wvsuffix.;(?<model>[^;]+): For entries without; wv, this captures all characters after the final semicolon.
Test Results Against Your Examples
- First User-Agent:
Mozilla/2.0 (Linux; Android 2.0; KK; SAMSUNG SM-G900H Build/LRX21T) AppleWebKit- Captures:
SAMSUNG SM-G900H Build/LRX21T
- Captures:
- Second User-Agent:
Mozilla/5.0 (Linux; Android 5.0; SAMSUNG SM-G900H Build/LRX21T) AppleWebKit- Captures:
SAMSUNG SM-G900H Build/LRX21T
- Captures:
- Third User-Agent:
Mozilla/5.0 (Linux; Android 5.1; XT1032 Build/LPBS23.13-56-2; wv) AppleWebKit- Captures:
XT1032 Build/LPBS23.13-56-2
- Captures:
内容的提问来源于stack exchange,提问作者Giorgi Nakeuri
相关产品推荐
相关产品推荐

