2014-09-13 41 views
3

我試圖創造一個Python正則表達式,兜攬,這將匹配形式用於匹配單行和多行註釋的Python正則表達式。

// some comment 

/* comment 
    more comment */ 

所以,我想

t_COMMENT = r'//.+ | /\*.+\*/' 

,但是這並未評論不允許多行註釋,當我嘗試使用'點匹配所有'選項解決此問題時,如

t_COMMENT = r'//.+ | (?s) /\*.+\*/' 

它導致'//'註釋類型匹配很多行。另外,如果我嘗試有兩個獨立的正則表達式像

t_COMMENT = r'//.+' 
t_COMMENT2 = r'(?s) /\*.+\*/' 

的「//」註釋類型仍然匹配多行,就好像點匹配的所有選項。

有人知道如何解決這個問題嗎?

+1

我強烈懷疑這是一個壞主意。嘗試使用複雜的正則表達式進行太多高級別(語法)解析是創建詞法分析器/解析器系統的對立面。我建議你有單行註釋的標記,多行開始和結束。圍繞解析器構建的語法可以放棄在多行開始和結束之間找到的所有輸入。 – 2014-09-13 12:17:25

+0

你能根據你的想法給出答案嗎? – Zvika 2014-09-28 15:40:40

回答

3

下面的正則表達式將匹配兩種類型的評論,

(?://[^\n]*|/\*(?:(?!\*/).)*\*/) 

DEMO

>>> s = """// some comment 
... 
... foo 
... bar 
... foobar 
... /* comment 
... more comment */ bar""" 
>>> m = re.findall(r'(?://[^\n]*|/\*(?:(?!\*/).)*\*/)', s, re.DOTALL) 
>>> m 
['// some comment', '/* comment\n more comment */'] 
+0

不需要偷看正斜槓...... – isedev 2014-09-13 11:46:55

0

這裏有阿維納什的解決方案輕微變化。

pat = re.compile(r'(?://.*?$)|(?:/\*.*?\*/)', re.M|re.S)

2

根據PLY Doc它可以用 '條件詞法' 來完成。 它可能比複雜的正則表達式更易讀,更易於調試。 他們給出的例子稍微複雜一點,因爲它會跟蹤嵌套層次以及塊內的內容。然而,你的情況更簡單,因爲你不需要所有的信息。

多行註釋代碼應該是這樣的:

# I'd prefer 'multi_line_comment', but it appears that 
# state names cannot have underscore in them 
states = (
    ('multiLineComment','exclusive'), 
) 

def t_multiLineComment_start(t): 
    r'/\*' 
    t.lexer.begin('multiLineComment')   

def t_multiLineComment_end): 
    r'\*/' 
    t.lexer.begin('INITIAL')   

def t_multiLineComment_newline(t): 
    r'\n' 
    pass 

# catch (and ignore) anything that isn't end-of-comment 
def t_multiLineComment_content(t): 
    r'[^(\*/)]' 
    pass 

當然,你必須有另一個規則,常規狀態下,爲//意見。

0

此重新也許有用

(/\*(.|\n)*?*/)|(//.*) 
相關問題