Case insensitive token matching

余生颓废 提交于 2019-12-14 01:33:23

问题


Is it possible to set the grammar to match case insensitively.

so for example a rule:

checkName = 'CHECK' Word;

would match check name as well as CHECK name


回答1:


Creator of PEGKit here.

The only way to do this currently is to use a Semantic Predicate in a round-about sort of way:

checkName = { MATCHES_IGNORE_CASE(LS(1), @"check") }? Word Word;

Some explanations:

  • Semantic Predicates are a feature lifted directly from ANTLR. The Semantic Predicate part is the { ... }?. These can be placed anywhere in your grammar rules. They should contain either a single expression or a series of statements ending in a return statement which evaluates to a boolean value. This one contains a single expression. If the expression evaluates to false, matching of the current rule (checkName in this case) will fail. A true value will allow matching to proceed.

  • MATCHES_IGNORE_CASE(str, regexPattern) is a convenience macro I've defined for your use in Predicates and Actions to do regex matches. It has a case-sensitive friend: MATCHES(str, regexPattern). The second argument is an NSString* regex pattern. Meaning should be obvious.

  • LS(num) is another convenience macro for your use in Predicates/Actions. It means fetch a Lookahead String and the argument specifies how far to lookahead. So LS(1) means lookahead by 1. In other words, "fetch the string value of the first upcoming token the parser is about to try to match".

  • Notice that I'm still matching Word twice at the end there. The first Word is necessary for matching 'check' (even though it was already tested in the predicate, it was not matched and consumed). The second Word is for your name or whatever.

Hope that helps.



来源:https://stackoverflow.com/questions/23161176/case-insensitive-token-matching

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!