正则表达式升级到Java正则表达式

时间:2016-05-30 08:47:04

标签: java regex sublimetext3

我有这个正则表达式删除.c文件中的注释(sublime 3 regex)

Data.Vector.replicateM :: Monad m => Int -> m a -> m (Vector a)

我可以在java中使用此正则表达式以编程方式使用它吗? 如果没有,我应该使用什么正则表达式? (P.S.我知道,有点愚蠢地问我们,但我根本不知道如何正则表达式)

2 个答案:

答案 0 :(得分:1)

请注意,模式中有太多冗余捕获组,(.|\n)+?结构效率非常低,可能会导致Java出现严重问题(与任何其他正则表达式引擎一样)。

您可以使用更多简化表达式,不应导致多余的回溯:

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

请参阅regex demo。将其与Pattern.MULTILINE标志一起使用(或在模式的开头添加(?m))。

模式说明

  • (?:^|\s+)//.* - (您的2个(^\/\/.*)|(\s+\/\/.*)分支合并)单行注释在字符串的开头或在前1个空格后跟//子字符串(包括这些空格和向前)斜杠)
  • | - 或
  • /\*[^*]*\*+(?:[^/*][^*]*\*+)*/ - 匹配多行/**/评论

Java声明:

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

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, "")); 

答案 1 :(得分:0)

这应该有效:(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)|(?://.*)

Ideone Demo