Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

jcon模式 #10

Open
acodercc opened this issue May 17, 2015 · 0 comments
Open

jcon模式 #10

acodercc opened this issue May 17, 2015 · 0 comments

Comments

@acodercc
Copy link
Owner

#1 无限重复的匹配

如匹配变量列表int ab,cd,efg;
或者css的declaration列表background:red;color:green;font-size:16px;

主要是利用jcon.or解析器组合子,会返回多个子解析器中最长成功匹配的子解析器。
首先来看int ab,cd,efg;的匹配方式:

var jcon = require('jcon');
var type = jcon.or(jcon.string('int'),jcon.string('double')).setAst('type');  //各种类型
var variable_name = jcon.regex(/[a-zA-Z]\w*/).setAst('variable_name');  //英文字符先导的变量名
var comma = jcon.string(',');
var semicolon = jcon.string(';');

var variable_name_has_comma = jcon.seq(variable_name, comma).noLookhead(semicolon);
var space_list = jcon.regex(/\s/).least(1);
var variable_list = jcon.or(variable_name, variable_name_has_comma).least(1);
var declaration_stmt = jcon.seq(type, space_list, variable_list, semicolon);

console.log( declaration_stmt.parse('int  ab;').ast() );
console.log( declaration_stmt.parse('int  ab,cd;').ast() );
console.log( declaration_stmt.parse('int  ab,;').success );
var variable_list = jcon.or(variable_name, variable_name_has_comma).least(1);

这句实现了最少一个的variable_name的重复,注意jcon.or和jcon.noLookhead的运用:
1 jcon.or组合子将返回最长成功匹配的子解析器,所以ab, cd, 都是variable_name_has_comma进行匹配的。
2 jcon.noLookhead让 ab,; 这种输入串的模式匹配失败,variable_name_has_comma是noLookhead(';')的
#2 skip的运用

skip将会让一个解析器的解析结果不进入seq和times等合并解析结果的解析器组合子的解析结果中

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant