如何在lex中获得正则表达式的这种模式匹配 [英] How to get such pattern matching of regular expression in lex

查看:287
本文介绍了如何在lex中获得正则表达式的这种模式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查正则表达式中的特定模式,但是我做不到.输入应该像

Hi I want to check a specific pattern in regular expression but I'm failed to do that. Input should be like

名词 单词名称:单词含义

我成功获取了名词 wordname ,但是无法设计出单词含义的模式.我的代码是:

I'm successful getting noun and wordname but couldn't design a pattern for word meaning. My code is :

int state;
char *meaning;
char *wordd; 

^verb   { state=VERB; }
^adj    { state = ADJ; }
^adv    { state = ADV; }
^noun   { state = NOUN; }
^prep   { state = PREP; }
^pron   { state = PRON; }
^conj   { state = CONJ; }

//my try but failed
[:\a-z]   {
meaning=yytext;
printf(" Meaning is getting detected %s", meaning);

}

[a-zA-Z]+  {
word=yytext;

}

示例输入:

noun john:This is a name

现在word应该等于johnmeaning应该等于This is a name.

Now word should be equal to john and meaning should be equal to This is a name.

推荐答案

同意采用lex状态(也称为开始条件)(奇怪,但没有有用的教程)

Agreeing that lex states (also known as start conditions) are the way to go (odd, but there are no useful tutorials).

简而言之:

  • 您的应用程序可以组织为州,其中一个用于名词",一个用于"john",另一个用于定义(在冒号之后).
  • 在lex文件顶部的
  • 声明状态,例如

  • your application can be organized as states, using one for "noun", one for "john" and one for the definition (after the colon).
  • at the top of the lex file, declare the states, e.g.,

%s TYPE NAME VALUE

您的程序在操作中使用BEGIN()宏来切换状态,例如,

your program switches states using the BEGIN() macro, in actions, e.g.,

{ BEGIN(TYPE); }

NAME状态下,您的词法分析器会查找您认为名称应为的任何内容,例如

in the NAME state, your lexer looks for whatever you think a name should be, e.g.,

<NAME>[[:alpha:]][[:alnum:]]+ { my_name = strdup(yytext); }

名称以冒号结尾,所以

<NAME>":" { BEGIN(VALUE); }

该值就是直到行尾的所有内容,例如

the value is then everything until the end of the line, e.g.,

<VALUE>.* { my_value = strdup(yytext); BEGIN(INITIAL); }

进一步阅读:

  • Start conditions (flex documentation)
  • Introduction to Flex

这篇关于如何在lex中获得正则表达式的这种模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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