malak
malak

Reputation: 27

regex match user agent with and without some word

To differentiate a user-agent Mobile and a User Agent Tablet, i wrote regex like these :

For Mobile:

.+iPhone.+|.+Android.+Mobile.+

For Tablet:

.+iPad.+Mobile.+|.+Android.+[^Mobile].+

And try on these user agent for tablet:

Mozilla/5.0 (iPad; CPU OS 7_0 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A465 Safari/9537.53 

-> OK Tablet

Mozilla/5.0 (Linux; Android 4.3; Nexus 10 Build/JSS15Q) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2307.2 Safari/537.36

-> OK Tablet

Mozilla/5.0 (Linux; Android 4.2.2; GT-I9505 Build/JDQ39) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.59 Mobile Safari/537.36

-> OKTablet and this is not a tablet...

The last one is considered like the others, but this is a user agent for a mobile and this is not what i want..

I need to write my regex with a pattern which considerate as valid a user-agent string containing Android but strictly not containing "Mobile"

an idea anyone ? thanks !

Upvotes: 1

Views: 1254

Answers (1)

anubhava
anubhava

Reputation: 785266

This regex should work for you to identify tablet:

.+(?:iPad.+Mobile|Android(?!.+Mobile)).+

Negative character class i.e. [^Mobile] doesn't mean not a Mobile. It just negates individual characters. So [^Mobile] will match a single character that is not one of these character inside [...].

RegEx Demo

Upvotes: 1

Related Questions