4

Here is what i've got so far:

/(netscape)|(navigator)\/(\d+)(\.(\d+))?/.test(UserAgentString.toLowerCase()) ? ' netscape'+RegExp.$3+RegExp.$4 : ''

I'm trying to do several different things here.

(1). I want to match either netscape or navigator, and it must be followed by a single slash and one or more digits.

(2). It can optionally follow those digits with up to one of: one period and one or more digits.

The expression should evaluate to an empty string if (1) is not true.

The expression should return ' netscape8' if UserAgentString is Netscape/8 or Navigator/8.

The expression should return ' netscape8.4' if UserAgentString is Navigator/8.4.2.

The regex is not working. In particular (this is an edited down version for my testing, and it still doesn't work):

// in Chrome this produces ["netscape", "netscape", undefined, undefined]
(/(netscape)|(navigator)\/(\d+)/.exec("Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.7.5) Gecko/20060912 Netscape/8.1.2".toLowerCase()))

Why does the 8 not get matched? Is it supposed to show up in the third entry or the fourth?

There are a couple things that I want to figure out if they are supported. Notice how I have 5 sets of capture paren groups. group #5 \d+ is contained within group #4: \.(\d+). Is it possible to retrieve the matched groups?

Also, what happens if I specify a group like this? /(\.\d+)*/ This matches any number of "dot-number" strings contatenated together (like in a version number). What's RegExp.$1 supposed to match here?

4

3 に答える 3

3

あなたの「または」表現は、あなたが思っていることをしていません。

簡単に言うと、あなたはこれをやっています:

(a)|(b)cde

aまたは のいずれかに一致しますbcde

「または」式を括弧で囲みます。これは、またはのいずれか((a)|(b))cdeに一致します。acdebcde

http://regexpal.com/は、正規表現の構文をすばやくチェックするための非常に便利なツールです。

于 2012-06-28T18:59:09.403 に答える
1

正規表現 (netscape|navigator)\/(\d+(?:\.\d+)?) は 2 つのグループを返します (一致が見つかった場合):

  1. ネットスケープまたはナビゲーター
  2. 名前の後ろの数字

    var m = /(netscape|navigator)\/(\d+(?:\.\d+)?)/.exec(text); 
    if (m != null) { 
      var r = m[1] + m[2]; 
    }
    
于 2012-06-28T18:54:20.663 に答える
0

(....) グループを作成します。そのグループ内のすべてが、そのグループの変数とともに返されます。

以下は、ピリオドで区切られたバージョンの最初の 2 つの数字とnetscape一致します。navigator

          $1                       $2
 |------------------|        |------------|
/(netscape|navigator)[^\/]*\/((\d+)\.(\d+))/

最終的なコードは次のようになります。

/(netscape|navigator)[^\/]*\/((\d+)\.(\d+))/.test(
     navigator.userAgent.toLowerCase()
) ? 'netscape'+RegExp.$2 : ''

どちらがあなたに与えるでしょう

netscape5.0

これらの素晴らしいツッツをチェックしてください (他にもたくさんあります):

于 2012-06-28T19:13:40.493 に答える