2016-07-31 187 views
1

我有正則表達式,應該刪除評論(多,單行)正則表達式不匹配所有

(\s*\/\/.*)|((\/\*)(.|\n)+?(\*\/)) 

當我檢查了它的崇高,或在網站上,它爲我工作正常。 但是當我在程序中使用它時,它無法正常工作。 這就是我的意思。

/** 
* Base class from which all RMI-IIOP stubs must inherit. 
*/ 

public abstract class Stub extends ObjectImpl 
implements java.io.Serializable { 

// This can only be set at object construction time (no sync necessary). 
private transient StubDelegate stubDelegate = null; 

regexp只匹配單行註釋,但在其他文本編輯器中它適用於所有類型。

這裏是我的代碼:

FileInputStream fis = new FileInputStream(filePath); 
    BufferedReader br = new BufferedReader(new InputStreamReader(fis)); 
    String strLine; 
    while ((strLine = br.readLine()) != null) { 
     Matcher m = Pattern.compile(delCommentsPattern,Pattern.MULTILINE).matcher(strLine); 
     while (m.find()) { 
      String b = m.group(); 
      System.out.println(b); 
    } 
} 

我在做什麼錯?

UPD:添加delCommentsPattern:

private String delCommentsPattern ="(\\s*\\/\\/.*)|((\\/\\*)(.|\\n)+?(\\*\\/))"; 

UPD2:我,已經做了,有什麼RAVI建議,但現在我有一個例外,當我使用它在更大的文件:

Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException 
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1774) 
    at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657) 
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86) 
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238) 
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191) 
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59) 
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58) 
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) 
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56) 
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) 
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56) 
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) 
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74) 
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49) 
    at javafx.event.Event.fireEvent(Event.java:198) 
    at javafx.scene.Node.fireEvent(Node.java:8411) 
    at javafx.scene.control.Button.fire(Button.java:185) 
    at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182) 
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96) 
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89) 
    at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218) 
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80) 
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238) 
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191) 
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59) 
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58) 
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) 
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56) 
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) 
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56) 
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) 
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74) 
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54) 
    at javafx.event.Event.fireEvent(Event.java:198) 
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3757) 
    at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485) 
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762) 
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494) 
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:380) 
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:294) 
    at java.security.AccessController.doPrivileged(Native Method) 
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(GlassViewEventHandler.java:416) 
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389) 
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:415) 
    at com.sun.glass.ui.View.handleMouseEvent(View.java:555) 
    at com.sun.glass.ui.View.notifyMouse(View.java:937) 
    at com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method) 
    at com.sun.glass.ui.gtk.GtkApplication.lambda$null$49(GtkApplication.java:139) 
    at java.lang.Thread.run(Thread.java:745) 
Caused by: java.lang.reflect.InvocationTargetException 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
    at java.lang.reflect.Method.invoke(Method.java:498) 
    at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71) 
    at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
    at java.lang.reflect.Method.invoke(Method.java:498) 
    at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275) 
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1769) 
    ... 48 more 
Caused by: java.lang.StackOverflowError 
    at java.util.regex.Pattern$LazyLoop.match(Pattern.java:4843) 
    at java.util.regex.Pattern$GroupTail.match(Pattern.java:4717) 
    at java.util.regex.Pattern$BranchConn.match(Pattern.java:4568) 
    at java.util.regex.Pattern$CharProperty.match(Pattern.java:3777) 
    at java.util.regex.Pattern$Branch.match(Pattern.java:4604) 
    at java.util.regex.Pattern$GroupHead.match(Pattern.java:4658) 
    at java.util.regex.Pattern$LazyLoop.match(Pattern.java:4847) 
    at java.util.regex.Pattern$GroupTail.match(Pattern.java:4717) 
    at java.util.regex.Pattern$BranchConn.match(Pattern.java:4568) 
    at java.util.regex.Pattern$CharProperty.match(Pattern.java:3777) 
    at java.util.regex.Pattern$Branch.match(Pattern.java:4604) 
    at java.util.regex.Pattern$GroupHead.match(Pattern.java:4658) 
    at java.util.regex.Pattern$LazyLoop.match(Pattern.java:4847) 
    at java.util.regex.Pattern$GroupTail.match(Pattern.java:4717) 
    at java.util.regex.Pattern$BranchConn.match(Pattern.java:4568) 
    at java.util.regex.Pattern$CharProperty.match(Pattern.java:3777) 
    at java.util.regex.Pattern$Branch.match(Pattern.java:4604) 
    at java.util.regex.Pattern$GroupHead.match(Pattern.java:4658) 
    at java.util.regex.Pattern$LazyLoop.match(Pattern.java:4847) 
    at java.util.regex.Pattern$GroupTail.match(Pattern.java:4717) 
    at java.util.regex.Pattern$BranchConn.match(Pattern.java:4568) 
    at java.util.regex.Pattern$CharProperty.match(Pattern.java:3777) 
    at java.util.regex.Pattern$Branch.match(Pattern.java:4604) 
    at java.util.regex.Pattern$GroupHead.match(Pattern.java:4658) 
    at java.util.regex.Pattern$LazyLoop.match(Pattern.java:4847) 
    at java.util.regex.Pattern$GroupTail.match(Pattern.java:4717) 
    at java.util.regex.Pattern$BranchConn.match(Pattern.java:4568) 
    at java.util.regex.Pattern$CharProperty.match(Pattern.java:3777) 
+1

您好,歡迎!你能不能顯示你設置'delCommentsPattern'的地方?你可以編輯你的問題。 – Mariano

回答

0

這是行不通的,因爲你是線加工生產線。

首先,您需要讀取字符串中的完整文件。然後使用正則表達式。

String strLine; 
StringBuffer sb = new StringBuffer(""); 
while ((strLine = br.readLine()) != null) { 
    sb.append(strLine + "\n"); 
} 

Matcher m = Pattern.compile(delCommentsPattern,Pattern.MULTILINE).matcher(sb.toString()); 
while (m.find()) { 
    String b = m.group(); 
    System.out.println(b); 
} 
+0

我已經做到了,但現在我有一個例外。查看UPD – villat

+0

我使用了相同的delCommentsPattern。你得到什麼異常? – RAVI

+0

的描述。 請注意,我使用較大的文件(70kb) – villat

4

由於您逐行讀取文件,您的正則表達式無法匹配跨越多行的文本。您需要首先將整個文件讀入單個字符串,然後執行while循環。

但要注意,你的正則表達式與下面的代碼,這在它看起來像它的問題開始註釋:

List<File> files = FileUtils.find("src/*.java"); // Note the /* 

取而代之的是正則表達式,你應該使用Java的分詞器和過濾器的輸出徵求意見。 https://github.com/javaparser/javaparser看起來就像是這份工作的適當工具。它甚至有一些test cases分析評論。

-1

如果我理解正確的是你正在嘗試做的(即提取評論)嘗試用這個字符串作爲Java中的正則表達式:

String regex = "(/\\*\\*.*\\*/)|(//.*?$)"; 

順便說一句,你必須確保你逃跑的星號和其他保留字符。另一件事是你需要閱讀文件,如果你想做多行的正則表達式(即如果你的正則表達式正在尋找多行註釋,你不能在一行上匹配)。

務必使用DOTALL和多

代碼示例:

public static void main(String[] args) throws Exception { 
    String text = readStream(new FileInputStream("test.txt")); 
    Matcher m = Pattern.compile("(/\\*\\*.*\\*/)|(//.*?$)", Pattern.MULTILINE | Pattern.DOTALL).matcher(text); 
    while (m.find()) { 
     String b = m.group(); 
     System.out.println("GROUP: "+b); 
    } 
} 

public static String readStream(InputStream is) { 
    StringBuilder sb = new StringBuilder(512); 
    try { 
     Reader r = new InputStreamReader(is, "UTF-8"); 
     int c = 0; 
     while ((c = r.read()) != -1) { 
      sb.append((char) c); 
     } 
    } catch (IOException e) { 
     throw new RuntimeException(e); 
    } 
    return sb.toString(); 
} 
+1

切勿在Java中使用'(。| \\ n)+?',在DOTALL修飾符中使用'。*?'。 –

1

正如其他人所說,在運行此正則表達式之前,必須將整個文件讀入字符串。

注意的是,爲了分析評論,你必須分析同時
時間,否則任何一個可以隱藏在其他的。

這是弦的正則表達式。
由於您正在刪除評論,因此此正則表達式會保留格式,因此它在移除後不會看起來連接在一起,因此
看起來不會連接在一起。

"(?m)((?:(?:^[ \\t]*)?(?:/\\*[^*]*\\*+(?:[^/*][^*]*\\*+)*/(?:[ \\t]*\\r?\\n(?=[ \\t]*(?:\\r?\\n|/\\*|//)))?|//(?:[^\\\\]|\\\\(?:\\r?\\n)?)*?(?:\\r?\\n(?=[ \\t]*(?:\\r?\\n|/\\*|//))|(?=\\r?\\n))))+)|(\"[^\"\\\\]*(?:\\\\[\\S\\s][^\"\\\\]*)*\"|'[^'\\\\]*(?:\\\\[\\S\\s][^'\\\\]*)*'|(?:\\r?\\n|[\\S\\s])[^/\"'\\\\\\s]*)" 

全部替換爲$2

說明(如果需要)

(?m)        # Multi-line modifier 
    (        # (1 start), Comments 
     (?: 
      (?:^[ \t]*)?     # <- To preserve formatting 
      (?: 
        /\*        # Start /* .. */ comment 
        [^*]* \*+ 
        (?: [^/*] [^*]* \*+)* 
       /        # End /* .. */ comment 
        (?:        # <- To preserve formatting 
         [ \t]* \r? \n          
         (?= 
          [ \t]*     
          (?: \r? \n | /\* | //) 
         ) 
       )? 
       | 
        //        # Start // comment 
        (?:        # Possible line-continuation 
         [^\\] 
        | \\ 
         (?: \r? \n)? 
       )*? 
        (?:        # End // comment 
         \r? \n        
         (?=        # <- To preserve formatting 
          [ \t]*       
          (?: \r? \n | /\* | //) 
         ) 
        | (?= \r? \n) 
       ) 
      ) 
     )+        # Grab multiple comment blocks if need be 
    )        # (1 end) 

|         ## OR 

    (        # (2 start), Non - comments 
     " 
     [^"\\]*       # Double quoted text 
     (?: \\ [\S\s] [^"\\]*)* 
     " 
    | ' 
     [^'\\]*       # Single quoted text 
     (?: \\ [\S\s] [^'\\]*)* 
     ' 
    | (?: \r? \n | [\S\s])   # Linebreak or Any other char 
     [^/"'\\\s]*      # Chars which doesn't start a comment, string, escape, 
             # or line continuation (escape + newline) 
    )        # (2 end)