使用正则表达式验证用户代理 [英] Validate Useragent with Regex

查看:32
本文介绍了使用正则表达式验证用户代理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试验证具有以下格式的用户代理

Mozilla/5.0 (Linux; U; Android ; ;  Build/) AppleWebKit/(KHTML, like Gecko) Version/4.0 Mobile Safari/

用户代理可以是即

Mozilla/5.0 (Linux; U; Android 4.2.2; en-us; AFTB Build/JDQ39) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30

到目前为止我的正则表达式是

Mozilla\/5\.0 \(Linux; U; Android (\d+\.)?(\d+\.)?(\*|\d+); [az]{2}-[az]{2} (AFTA|AFTN|AFTS|AFTB|AFTT|AFTM|AFTKMST12|AFTRS) 构建\/([A-Z0-9])\) AppleWebKit\/(\d+\.)?(\*|\d+) \(KHTML, like Gecko\) Version\/4\.0 Mobile Safari\/(\d+\.)?(\*|\d+)

测试:https://regex101.com/r/nXKYBB/1>

但它不匹配.有什么问题吗?

解决方案

en-de+ 之后你已经错过了一个 ;[A-Z0-9]:

Mozilla\/5\.0 \(Linux; U; Android (\d+\.)?(\d+\.)?(\*|\d+); [az]{2}-[az]{2}; (AFTA|AFTN|AFTS|AFTB|AFTT|AFTM|AFTKMST12|AFTRS) Build\/([A-Z0-9]+)\) AppleWebKit\/(\d+\.)?(\*|\d+) \(KHTML, like Gecko\) Version\/4\.0 Mobile Safari\/(\d+\.)?(\*|\d+)

查看正则表达式演示

请注意,如果您不打算在以后使用这些捕获的子值,则匹配非捕获组 (?:...) 可能是一个好主意,而不是捕获组,并且使用 \s 匹配空格.

此外,如果您打算匹配整个字符串,请使用 ^$ 包裹模式.

I'm trying to validate a useragent which has the following format

Mozilla/5.0 (Linux; U; Android <android>; <locale>; <device> Build/<build>) AppleWebKit/<webkit> (KHTML, like Gecko) Version/4.0 Mobile Safari/<safari>

The useragent could be i.e.

Mozilla/5.0 (Linux; U; Android 4.2.2; en-us; AFTB Build/JDQ39) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30

My regex so far is

Mozilla\/5\.0 \(Linux; U; Android (\d+\.)?(\d+\.)?(\*|\d+); [a-z]{2}-[a-z]{2} (AFTA|AFTN|AFTS|AFTB|AFTT|AFTM|AFTKMST12|AFTRS) Build\/([A-Z0-9])\) AppleWebKit\/(\d+\.)?(\*|\d+) \(KHTML, like Gecko\) Version\/4\.0 Mobile Safari\/(\d+\.)?(\*|\d+)

Test: https://regex101.com/r/nXKYBB/1

But it didn't match. What is wrong with it?

解决方案

You have missed a ; after en-de and + after [A-Z0-9]:

Mozilla\/5\.0 \(Linux; U; Android (\d+\.)?(\d+\.)?(\*|\d+); [a-z]{2}-[a-z]{2}; (AFTA|AFTN|AFTS|AFTB|AFTT|AFTM|AFTKMST12|AFTRS) Build\/([A-Z0-9]+)\) AppleWebKit\/(\d+\.)?(\*|\d+) \(KHTML, like Gecko\) Version\/4\.0 Mobile Safari\/(\d+\.)?(\*|\d+)

See the regex demo

Note that it might be a good idea to match non-capturing groups, (?:...), rather than capturing groups if you do not plan to use those captured subvalues later, and use \s to match whitespace.

Also, if you plan to match the whole string, wrap the pattern with ^ and $.

这篇关于使用正则表达式验证用户代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆