yytext中的flex中仅匹配字符串的一部分 [英] Only part of matched string in flex in yytext

查看:378
本文介绍了yytext中的flex中仅匹配字符串的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新手,但是我想知道是否可以使用flex以正则表达式解析某些内容,而yytext只能是匹配序列的一部分.例如:@abcd{efgh,.我想先匹配一次abcd,然后再使用它efgh,,但是我需要使用@和{来匹配它们.这是否可能,或者我稍后必须在C中完全处理它吗?

I'm a newbie but I would like to know if I can, with flex, parse something with regex in a way yytext would only be part of the matched sequence. For example: @abcd{efgh,. I would like to match abcd once and use it then efgh, but I need to use the @ and the { to match them. Is this possible or do I have to process it entirely later in C?

推荐答案

您可以在'/'运算符中使用以下上下文.对于eaxmple,

You can use following context with the '/' operator. For eaxmple,

abcd/efgh

仅当字符串"abcd"后跟"efgh"时才与字符串匹配,后一个字符串留在输入中,因此它将是下一个匹配的标记(的一部分).

will match the string "abcd" only if its followed by "efgh", with the latter string being left on the input, so it will be (part of) the next matched token.

我不确定您对"@"和"{"的要求是什么—您要匹配它们但忽略它们,还是要将它们作为单独的令牌返回?对于前者,您可以使用"@abcd"/"{efgh",然后仅使用yytext + 1来获取"abcd".后者更为复杂,但是可以使用flex的状态来完成.您可能会执行以下操作:

I'm not sure exactly what you're asking about with the "@" and "{" however -- do you want to match them but just ignore them, or do you want to return them as seperate tokens? For the former you could use "@abcd"/"{efgh" and then just use yytext+1 to get "abcd". The latter is more complex, but it can be done using flex's states. You might do something like:

%x at

%%

"@"        { BEGIN(at); return *yytext; }
<at>"abcd" { BEGIN(INITIAL); return ABCD; }

仅在其自身匹配的"@"之后立即匹配"abcd".

to match an "abcd" only if its immediately after an "@" that was matched by itself.

您可以使用开始状态在flex中做很多复杂的事情,但是通常尝试解析非常规语言是一个坏主意-最好使用bison之类的解析工具.

You can do lots of complex things in flex with start states, but generally trying to parse a non-regular language is a bad idea -- you're better off using a parsing tool such as bison for that.

这篇关于yytext中的flex中仅匹配字符串的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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