正则表达“Url”之外的评论

时间:2012-03-21 02:16:21

标签: regex

希望从javascript中匹配 评论功能的网址。

Url的正则表达式:

((mailto\:|(news|(ht|f)tp(s?))\://){1}\S+)

给出了这个例子:

/* http://goog.le */
http://goog.le

它应该只匹配第二个。

到目前为止,我尝试了here这个正则表达式没有成功:

(/*)[^(*/)]*((mailto\:|(news|(ht|f)tp(s?))\://){1}\S+)

感谢您的建议

3 个答案:

答案 0 :(得分:1)

一般来说,使用正则表达式进行这种解析很困难(但肯定不是不可能) - 你必须做出假设,例如输入结构良好。

首先请注意,在你的正则表达式中,{1}是多余的,因此可以删除。

您可以执行以下操作,只有在不是后跟*/(没有匹配的/*)时,才会匹配该网址。逻辑是,如果 后跟*/,它可能在评论中:

((mailto\:|(news|(ht|f)tp(s?))\://)\S+)(?!([^*/]|\*[^/]|/[^*])*\*/)

当然,如果您在源中*/而没有匹配的/*,则会失败,例如

/* http://goog.le */ # this won't match
http://goog.le       # this will match
http://google/ "*/fdsa" # this won't match!

我认为你采取的任何正则表达式方法都会在某种程度上依赖于输入结构良好 - 评论是平衡的等等。

(如果您使用的是javascript,是否可以使用某种XML解析?这样可以更好地 ,并且可能允许您在任何情况下忽略注释)。

答案 1 :(得分:1)

您可以使用替换并执行http://jsfiddle.net/92ma8/之类的操作,这些操作适用于字符串和转义。

// remove comments
// if you want to remove single line comments as well add: |\/\/.*
var nocomments = code.replace(/("(?:[^"\\]*|\\.)*"|'(?:[^'\\]*|\\.)*')|\/\*[^]*?\*\//g, "$1");

// do your matching
var result = nocomments.match(/[a-z]+:\/\/\S+/gi);

在此字符串中:

/* http://aaa.com */               
http://bbb.com                     
//  http://ccc.com                 
http://ddd.com "will \"*/ /*work" 
"/* http://eee.com */ works"

匹配:

http://bbb.com
http://ccc.com
http://ddd.com
http://eee.com

答案 2 :(得分:0)

((?<!\/\*)) #Negative lookbehind
  ((mailto\:|(news|(ht|f)tp(s?))\://)\S+)(?!([^*]|\*[^/])*\*/)
(
  ?(1) # Ensure the negative lookbehind has matched (Embedded Condition)
  (?!\*/) # Ensure the negative lookahead
) 

这是一个班轮

((?<!\/\*))((mailto\:|(news|(ht|f)tp(s?))\://)\S+)(?!([^*]|\*[^/])*\*/)(?(1)(?!\*/))