Regex problem for UserAgent Android

1

I'm trying to create a regex (for use in PHP) that can match the groups correctly and extract the information I need. In this case it is to get information from android useragent.

When the userAgent is like this:

  

p>

Of course, however, it has userAgent that has one more data, the "pt-br", like this:

  

User-Agent: Mozilla / 5.0 (Linux; U; Android 4.1.2; LG-E467f Build / JZO54K) AppleWebKit / 534.30 (KHTML, like Gecko) Version / 4.0 Mobile Safari / 534.30 >

I could not because the "en" is optional.

Follow what I've tried link

My regex is this:

(?P<browser>Android)\s(?P<major_version>\d+)\.(?P<minor_version>\d+\.?\d?);(?P<lang>\spt-br)?(?P<device>[ \w\-?]+)\s

Can anyone help me complete this regex? and I need it to match all groups, and when it does not have pt-br, just return empty.

    
asked by anonymous 05.09.2017 / 14:21

1 answer

0

Try using this Regex

(?P<browser>Android)\s(?P<major_version>\d+)\.(?P<minor_version>\d+\.?\d?);(?P<lang>\spt-br){0,1};{0,1}(?P<device>[ \w\-?]+)\s

You can test how it works here.

What did I do differently?
I include {0,1} after [...](?P<lang>\spt-br) and ;{0,1} making optional the existence of pt-br; after minor version, now it will capture only if it exists pt.

Considerations
I do not know if there is a possibility, but it is good to consider the existence of other browsers and other lang's, if you have this possibility use the operator "OR" ( | ) as in this example .

    
06.09.2017 / 15:09