简体   繁体   中英

Regex Sublime to Java regex

i have this regex to delete comments in .c file(sublime 3 regex)

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

Can i use this regex in java to use it programmatically? If not, what regex should i use? (PS i know, question us stupid a bit, but i don't know how to regex at all)

Note that you have too many redundant capture groups inside the pattern, and the (.|\\n)+? construct is very inefficient and may cause serious issues in Java (as with any other regex engine).

You can use a more streamlines expression that should not cause much redundant backtracking:

(?:^|\s+)//.*|/\*[^*]*\*+(?:[^/*][^*]*\*+)*/

See the regex demo . Use it with Pattern.MULTILINE flag (or add (?m) at the start of the pattern).

Pattern explanation :

  • (?:^|\\s+)//.* - (your 2 (^\\/\\/.*)|(\\s+\\/\\/.*) branches merged) single line comments at the start of a string or after the first 1+ whitespaces followed with // substring (including these whitespaces and forward slashes)
  • | - or
  • /\\*[^*]*\\*+(?:[^/*][^*]*\\*+)*/ - match multiline /**/ comments

Java declaration:

String pattern = "(?m)(?:^|\\s+)//.*|/\\*[^*]*\\*+(?:[^/*][^*]*\\*+)*/";

And a sample code :

String s =  "// Comment\ntex test\nMore text here // and comment 2\n/* More comments\nhere and\nhere */";
String pattern = "(?m)(?:^|\\s+)//.*|/\\*[^*]*\\*+(?:[^/*][^*]*\\*+)*/";
System.out.println(s.replaceAll(pattern, "")); 

This should work : (?:/\\\\*(?:[^*]|(?:\\\\*+[^*/]))*\\\\*+/)|(?://.*)

Ideone Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM