2010-03-26 55 views
1

大問題,我有一些內容是這樣的:在萊克斯正則表達式(詞法分析器)

author = "Marjan Mernik and Viljem Zumer", 
    title = "Implementation of multiple attribute grammar inheritance in the tool LISA", 
    year = 1999 

    author = "Manfred Broy and Martin Wirsing", 
    title = "Generalized 
      Heterogeneous Algebras and 
      Partial Interpretations", 
    year = 1983 

    author = "Ikuo Nakata and Masataka Sassa", 
    title = "L-Attributed LL(1)-Grammars are 
      LR-Attributed", 
    journal = "Information Processing Letters" 

,我需要趕上雙引號之間家居標題。我的第一次嘗試是這樣的:

^(" "|\t)+"title"" "*=" "*"\"".+"\","

惹人第一個例子,而不是其他兩個。另一個有多條線路,這就是問題所在。我雖然要改變的東西與\n的地方,讓多條線路,如:

^(" "|\t)+"title"" "*=" "*"\""(.|\n)+"\","

但是,這並沒有幫助,相反,它抓住一切

比我雖然,「我要的是雙引號之間,如果我抓到的一切,直到我找到另一個"其次,?這樣我可以知道我是在標題或沒有結束,無論是行數,像這樣:

^(" "|\t)+"title"" "*=" "*"\""[^"\""]+","

但是,這裏有一個問題...上面的例子沒有它,但雙引號符號(")可以在之間在標題聲明。例如:

title = "aaaaaaa \"X bbbbbb", 

是的,它總是會有一個反斜槓(\)。

任何建議來解決這個正則表達式?

+0

爲什麼你需要lex來做到這一點?你會有解析器嗎? – LB40 2010-03-27 00:52:22

回答

2

經典的正則表達式在雙引號匹配的字符串是:

\"([^\"]|\\.)*\" 

在你的情況,你會想是這樣的:

"title"\ *=\ *\"([^\"]|\\.)*\" 

PS:恕我直言,你把太多你的正則表達式中有很多引號,很難閱讀。

+0

Lex不能使用空格,它需要'「」'來匹配空格。這僅僅是因爲Lex的緣故,我通常不會在PHP等不同的語言(我最習慣於使用正則表達式)上做這件事。 – 2010-03-27 00:20:33

+1

你也可以使用''''來匹配大多數lex版本的空間 – 2010-03-27 00:42:18

+0

我相信'\'符合POSIX標準。請參閱http://www.opengroup.org/onlinepubs/009695399/utilities/lex.html,表格:lex中的轉義序列。 – rz0 2010-03-27 02:21:09

0

你可以使用啓動條件,以簡化每個單獨的模式,例如:

%x title 
%% 
"title"\ *=\ *\" { /* mark title start */ 
    BEGIN(title); 
    fputs("found title = <|", yyout); 
} 

<title>[^"\\]* { /* process title part, use ([^\"]|\\.)* to grab all at once */ 
    ECHO; 
} 

<title>\\. { /* process escapes inside title */ 
    char c = *(yytext + 1); 
    fputc(c, yyout); /* double escaped characters */ 
    fputc(c, yyout); 
} 

<title>\" { /* mark end of title */ 
    fputs("|>", yyout); 
    BEGIN(0); /* continue as usual */ 
} 

要使一個可執行文件:

$ flex parse_ini.y 
$ gcc -o parse_ini lex.yy.c -lfl 

運行:

$ ./parse_ini < input.txt 

哪裏input.txt是:

author = "Marjan\" Mernik and Viljem Zumer", 
title = "Imp\"lementation of multiple...", 
year = 1999 

輸出:

author = "Marjan\" Mernik and Viljem Zumer", 
found title = <|Imp""lementation of multiple...|>, 
year = 1999 

它通過'<|''|>'. Also替換周圍標題'"' '\「'`被替換 ' 」「' 內的標題。

+0

我已經使用了太多的啓動條件,這使事情變得複雜一點。另外,在一個正則表達式中捕獲所有東西更容易,因爲我需要將匹配傳遞給C函數。 – 2010-03-27 04:12:47

相關問題