以下は、適切なトークンを選択して JS 文字列から s 式を構築する正規表現です。これに続いて、これを行うためにどのように構築されているかを説明する巨大なブロック コメントが続きます。私は正規表現に慣れていないので、それを含めました。おそらく、これらの点の1つを理解していません。 私が理解していないのは、なぜ各一致 regex.exec() が同じ一致を 2 回繰り返し、リストとしてグループ化する必要があるのかということです。
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
一致がリストとして繰り返されるのはなぜですか?