2011-03-16 171 views
1

好吧,我一直在尝试在lex中找到一个正则表达式,它将识别输入字符串中类C的字符串文字。例如。在printf("stackoverflow")中,“stackoverflow”应该被识别为字符串文字。 我一直在尝试以下方法:如何在lex中识别扫描仪的字符串文字?

"[.]+" 
["][.]+["] 
\"[.]+\" 
[\"][.]+[\"] 
"""[.]+""" 

这些都不起作用。每次识别的词位是“孤独,我应该怎么做事先做人? 谢谢...

+0

可能重复的[正则表达式的字符串在柔性字面/法](HTTP ://stackoverflow.com/questions/2039795/regular-expression-for-a-string-literal-in-flex-lex) – kennytm 2011-03-16 19:42:14

回答

3

简单,试试这个:

\".*\"  printf("STRING[%s]", yytext); 
\'.*\'  printf("STRING[%s]", yytext); 

当编译和运行,快速测试表明它正确地解析字符串等

"hello world!" 
STRING["hello world!"] 
'hello world!' 
STRING['hello world!'] 
'john\'s cat' 
STRING['john\'s cat'] 
'mary said "hello!"' 
STRING['mary said "hello!"'] 
"frank said \"goodbye!\"" 
these are words "which contain" a string 
these are words STRING["which contain"] a string 

干杯, 克里斯