2011-03-16 170 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 

乾杯, 克里斯