简体   繁体   中英

Javascript regexp: how to create a single matching group

Scenario

I am trying to get the operating system details from the navigator.appVersion property.

So I tried the regexp.exec() method:

/\\(([a-z0-9 \\.]+)(?=;).*\\)|\\(([a-z0-9 \\.]+)\\)/i.exec(navigator.appVersion);

And here are the outcomes in different browsers:

  • Opera, Safari, Chrome

    ["(Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)", "Windows NT 6.1", undefined]

  • IE

    "[(Windows NT 6.1; WOW64; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3; rv:11.0)"_"Windows NT 6.1",undefined]

  • Firefox

    ["(Windows)", undefined, "Windows"]

So I am pretty happy with the regexp definition, the matching group correctly get the OS details. But...

Questions

  1. Why in the output array the matched group has got a different position across browsers?

  2. What is the 'undefined' element of the output array?

The undefined is the group that didn't match. You have a single alternation, each with a capture group.

This is your regex in detail.

   \(
   ( [a-z0-9 \.]+ )              # (1)
   (?= ; )
   .* 
   \)
|  
   \(
   ( [a-z0-9 \.]+ )              # (2)
   \)  

Not sure what you need to do, but you can use a single capture group to handle both

 # /\(([a-z0-9 .]+)(?:(?=;).*)?\)/i

 \(
 ( [a-z0-9 .]+ )               # (1)
 (?:
      (?= ; )
      .* 
 )?
 \)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM