2013-04-23 22 views
9

如何使用正則表達式找到這個模式?正則表達式來查找C風格塊評論

空調風格的塊註釋

/* xxxxxxxxxxxx */

+0

如果'/ *'在同一行和'//'後面,這意味着它不會開始評論? – Patashu 2013-04-23 03:04:46

+0

不,我不需要處理這種情況 – linquize 2013-04-23 03:07:15

+0

除了使用正則表達式,如果你想全力以赴,你可以使用語言解析器和C(或其他)語言語法。例子是yacc,javacc,antlr – 2013-04-23 03:41:15

回答

1

我強烈建議只使用一個解析器一樣的意見,但如果只是爲了好玩 - 從我的頭頂,你可以使用Ruby做這樣的事情,假設你已經知道如何從文件中獲取內容(請記住,這是非常粗糙,只是一個可能的指南 - prolly將無法工作開箱):

def one_liner_comment string 
    string.match /\/\*.*\*\// 
end 

def multi_liner_comment_start string 
    # if always checking for one_liner_comment in code would not need first !one_... 
    !one_liner_comment(string) && string.match(/\/\*/) 
end 

def multi_liner_comment_end string 
# if always checking for one_liner_comment in code would not need first !one_... 
!one_liner_comment(string) && string.match(/\*\//) 
end 

然後確定你只是在那裏

if one_liner(string) 
    inline = true 
elsif multi_liner_comment_start(string) 
    started = true 
elsif started && multi_liner_comment_end(string) 
    ended = true 
end 

然後執行任何你想做的事情,從你的意見從這裏開始。

if inline 
    # do whatever you want 
    one_liner = false 
elsif started && !ended 
    # do whatever you want -> append or create new string 
elsif started && ended 
    # do whatever you want -> append to string 
    started = false 
    ended = false 
end 

當然它也可以被清理......

20

嘗試使用

\/\*(\*(?!\/)|[^*])*\*\/ 

捕捉單行和多行塊註釋。它搜索/*後跟任意數量的任一:

  • 一個*未後跟一個/
  • 任何炭除了*

然後閉合*/一次。

+0

您不需要在單獨的分支中匹配空白字符; '[^ * /]'將它們覆蓋。所有的'| \ s'確實會打開你[災難性的回溯](http://www.regular-expressions.info/catastrophic.html)。此外,你需要從那裏得到那個斜線,否則你的正則表達式將無法將註釋與斜線內部的斜線相匹配。 – 2013-04-23 11:13:16

+0

更改爲您的建議(儘管OP表示,斜槓的評論似乎不成問題) – Campfire 2013-04-23 14:14:53

+0

爲什麼不能'/\*(.(?!\*/*/))**\*/'?首先是一個'/ *',然後是任何不是'* /'後面的字符,然後''/'' – zzh1996 2017-01-23 08:49:39