ANTLR4 RegEx 词法分析器模式 [英] ANTLR4 RegEx lexer modes

查看:32
本文介绍了ANTLR4 RegEx 词法分析器模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 XSD 中的 RegEx 开发一个 Regx 解析器.我之前的问题描述在这里:ANTLR4 parsing RegEx

I am working on a Regx parser for RegEx inside XSD. My previous problem was descrived here: ANTLR4 parsing RegEx

从那时起我就拆分了 Lexer 和 Parser.现在我在解析括号内的括号时遇到问题.它们应该被视为括号内的字符和外的分组标记.这是我的词法分析器语法:

I have split the Lexer and Parser since than. Now I have a problem parsing parantheses inside brackets. They should be treated as characters inside the brackets and as grouping tokens outside. This is my lexer grammar:

lexer grammar RegExLexer;

Char    : ALPHA ;
Int     : DIGIT ;

LBrack  : '[' ;//-> pushMode(modeRange) ;
RBrack  : ']' ;//-> popMode ;
LBrace  : '(' ;
RBrace  : ')' ;
Semi    : ';' ;
Comma   : ',' ;
Asterisk: '*' ;
Plus    : '+' ;
Dot     : '.' ;
Dash    : '-' ;
Question: '?' ;
LCBrace : '{' ;
RCBrace : '}' ;
Pipe    : '|' ;
Esc     : '\\' ;

WS : [ \t\r\n]+ -> skip ;

fragment DIGIT : [0-9] ;
fragment ALPHA : [a-zA-Z] ;

这是一个例子:

[0-9a-z()]+

我觉得我应该在括号上使用模式来改变 ALPHA 片段的行为.如果我复制片段,我会收到一条错误消息,提示我不能进行两次声明.我已经阅读了关于这个的参考,但我仍然不明白我应该做什么.

I feel like i should use modes on brackets to change the behaviour of ALPHA fragment. If I copy the fragment, I get an error saying I can't have the declaration twice. I have read the reference about this and I still don't get what i should do.

如何实现这些模式?

推荐答案

您将不得不在解析器中处理这个问题,而不是在词法分析器中.当词法分析器看到 '(' 时,它将返回标记 LBrace.对于词法分析器,没有关于在哪里看到标记的上下文.它只是将输入分割成标记.您必须定义解析规则,并在处理解析树时,然后,您可以确定括号内是否包含 LBrace.

You're going to have to handle this in the parser, not the lexer. When lexer sees a '(', it will return token LBrace. For lexer, there is no context as to where token is seen. It simply carves up the input into tokens. You will have to define parse rules and when processing parse tree, you can then determine was the LBrace inside brackets or not.

这篇关于ANTLR4 RegEx 词法分析器模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆