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);
Fiddle: http://jsfiddle.net/66Zfh/3/
正则表达式的解释。匹配一个连续的字符集,要求满足:
/ 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*/
单个加号 +
和加号和问号 +?
之间有区别。单个加号尝试匹配尽可能多的字符,而 +?
则仅匹配必要的字符以获取 RegExp 匹配结果。例如:123 使用 \d+? > 1 和 \d+ > 123
。
String.match
方法执行全局匹配,因为使用了全局标志 /g
。带有 g
标志的 match
函数返回一个由所有匹配子序列组成的数组。
当省略 g
标志时,只会选择第一个匹配项。数组将包含以下元素:
Index 0: <Whole match>
Index 1: <Group 1>
{foo.bar}
是什么情况? - Mark Byers