1

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?

0

1 Answer 1

1

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 $.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.