正则表达式需要将字符串拆分为"."

use*_*396 5 javascript regex

我需要在Javascript中使用正则表达式.我有一个字符串:

'*window.some1.some\.2.(a.b + ")" ? cc\.c : d.n [a.b, cc\.c]).some\.3.(this.o.p ? ".mike." [ff\.]).some5'
Run Code Online (Sandbox Code Playgroud)

我希望按周期分割这个字符串,以便得到一个数组:

[
    '*window',
    'some1',
    'some\.2',   //ignore the . because it's escaped
    '(a.b ? cc\.c : d.n [a.b, cc\.c])',  //ignore everything inside ()
    'some\.3',
    '(this.o.p ? ".mike." [ff\.])',
    'some5'
]
Run Code Online (Sandbox Code Playgroud)

什么正则表达式会这样做?

Rob*_*b W 7

var string = '*window.some1.some\\.2.(a.b + ")" ? cc\\.c : d.n [a.b, cc\\.c]).some\\.3.(this.o.p ? ".mike." [ff\\.]).some5';
var pattern = /(?:\((?:(['"])\)\1|[^)]+?)+\)+|\\\.|[^.]+?)+/g;
var result = string.match(pattern);
result = Array.apply(null, result); //Convert RegExp match to an Array
Run Code Online (Sandbox Code Playgroud)

小提琴:http://jsfiddle.net/66Zfh/3/
RegExp的解释.匹配一组连续的字符,满足:

/             Start of RegExp literal
(?:            Create a group without reference (example: say, group A)
   \(          `(` character
   (?:         Create a group without reference (example: say, group B)
      (['"])     ONE `'` OR `"`, group 1, referable through `\1` (inside RE)
      \)         `)` character
      \1         The character as matched at group 1, either `'` or `"`
     |          OR
      [^)]+?     Any non-`)` character, at least once (see below)
   )+          End of group (B). Let this group occur at least once
  |           OR
   \\\.        `\.` (escaped backslash and dot, because they're special chars)
  |           OR
   [^.]+?      Any non-`.` character, at least once (see below)
)+            End of group (A). Let this group occur at least once
/g           "End of RegExp, global flag"
        /*Summary: Match everything which is not satisfying the split-by-dot
                 condition as specified by the OP*/
Run Code Online (Sandbox Code Playgroud)

+和之间有区别+?.单个加号尝试匹配尽可能多的字符,而a +?只匹配获得RegExp匹配所必需的这些字符.示例:123 using \d+? > 1 and \d+ > 123.

String.match由于/g全局标志,该方法执行全局匹配.match带有该g标志的函数返回一个由所有匹配子序列组成的数组.

g省略该标志时,仅选择第一个匹配.然后,该数组将包含以下元素:

Index 0: <Whole match>
Index 1: <Group 1>
Run Code Online (Sandbox Code Playgroud)