正则表达式捕获单行评论

时间:2014-07-11 16:38:02

标签: java regex comments

在java中使用正则表达式,我想检测以 // 开头的单行JS注释。所以我想出的是 -

[^:]\/\/.*$

正则表达式上面没有捕获:

http://example.com

但它从后续字符串中抓取了高亮度部分(我能理解为什么):ab c // qqqqqqqqqq 的。但是我不希望捕获c(字符立即留给//)。

另外,我不希望下面的字符串被捕获:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%//Table for help essages ends%>  

我知道,这个话题多次被谴责。但没有什么能帮助我。所以我再次问这个问题。出于测试目的,我正在使用http://rubular.com/此站点。

任何人都可以帮助我。

解决方案:

(?<!http:|https:)\/\/.*(?<!>)\s$

要删除我们正在使用的其他类型的评论:

<!--(.|\s)*?-->
\/\*(.|\s)*?\*\/
<%--(.|\s)*?--%>

测试用例:

http://example.com
abc  //  qqqqqq>qqqq 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">   
<% // END: Modified for Bug # 1070 %>

// comment
/* comment */ program //comment


var ok = "not really"; 
// This is a comment
// Shouldn't this be a comment too?

var one = 't "stuff"\' now.'; // comment /* hola */ // lol

/* multiline comment
// still
/* still * * * * / */
something here

'string\' // string'; // comment /* comment
/regex/; // comment */* still-a-comment
' /**/ string ' /* "comment..."
// still-a-comment */ alert('isn\'t a comment!');
/\/* this isn't a comment! */; //* comment
/*
    //a comment... // still-a-comment
    12345
    "Foo /bar/ ""
*/
/*//Boo*/
/*/**/

1 个答案:

答案 0 :(得分:2)

如果您在评论之前没有冒号,并且评论不以&gt;结尾,(?<!:)\/\/.*(?<!\>)$  将满足您在问题上发布的所有案例。 如果您在评论之前确实有冒号,则可以指定
(?<!http:|https:)\/\/.*(?<!\>)$

或者另一个解决方案是(?<!http:|https:)\/\/[^\>]*$,它与包含&gt;的评论不匹配,放在任何地方。

相关问题