【发布时间】:2013-11-11 20:35:56
【问题描述】:
以下是一个正则表达式,它从 JS 字符串中挑选出相关的标记来构造一个 s 表达式。紧随其后的是一个巨大的块注释,记录了它是如何构建的。我包括它是因为我是正则表达式的新手,也许我不理解其中的一点。 我不明白的是为什么每个匹配 regex.exec() 返回的应该是相同的匹配重复两次并分组为一个列表?
var tx = /\s*(\(|\)|[^\s()]+|$)/g; // Create a regular expression
/* /1 234 5 6 7 /global search
1. \s : whitespace metacharacter
2. n* : matches any string that contains zero or more
occurrences of n
3. (a|b|c) : find any of the alternatives specified
4. \( : escaped open paren, match "(" (since parens are reserved
characters in regex)
5. \) : escaped close paren, match ")"
6. [^abc] : find any character not between the brackets
7. n+ : matches any string that contains at least one n
RESULT - Find matches that have zero or more leading whitespace characters (1+2)
that are one of the following (3): open paren (4) -OR- close paren (5)
-OR- any match that is at least one non-whitespace, non-paren character (6+7)
-OR- $, searching globally to find all matches */
var textExpression = "(1 2 3)";
var execSample;
for(var i =0; i < textExpression.length; i++){
execSample = tx.exec(textExpression)
display( execSample );
}
这是打印的内容:
(,(
1,1
2,2
3,3
),)
,
null
为什么匹配项作为列表重复?
【问题讨论】:
标签: javascript regex exec expression tokenize