正则表达式,用于干净的JavaScript注释类型// [英] Regular expression for clean javascript comments of type //

查看:114
本文介绍了正则表达式,用于干净的JavaScript注释类型//的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下REGEXP:

  $ output = preg_replace(/ \ / \ /(。 *)\\\\
/,,$ output);

代码运行良好但是!!!!,当URL (http: /this_is_not_a_comment.com/kickme),代码替换它...(http://)



您可以做些什么来不替换这些网址。



感谢,

解决方案

代码和评论之间。特别是,由于 // 的顺序可以是字符串或注释,所以您只需要区分字符串和注释。



下面是一个例子,可以这样做:

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

在替换函数中使用this,同时用第一个子模式的匹配替换匹配的字符串时,应该能够移除 // 样式注释



一些解释:


  • [^ /'] + 匹配任何不是注释开头的字符( // ... / * ... * / )或字符串
  • / \ *(?:[^ *] | \ * + [^ * /])* \ * + / 匹配 / * ... * / 样式注释

  • (?:[^\\ | | \\。)* 匹配双引号中的字符串

  • '(?:[^'\\ | | \\\。)*' 匹配单引号中的字符串
  • \ / \ /.* 最后匹配 // ... 样式注释



由于前三个构造分组在一个捕获组时,匹配的字符串可用,并且在用第一个子模式的匹配替换匹配的字符串时不会更改任何内容。只有匹配 // ... 样式注释时,第一个子模式的匹配才是空的,因此它被替换为空字符串。



但请注意,这可能会失败。我不太确定它是否适用于任何输入。


I´m using the following REGEXP:

$output = preg_replace( "/\/\/(.*)\\n/", "", $output );

The code works well BUT!!!!, when a URL like (http://this_is_not_a_comment.com/kickme), the code replaces it... (http://)

What can you do to no replace that URLs.

Thanks,

解决方案

You need a regular expression that can distinguish between the code and the comments. In particular, since the sequence of // can either be in a string or a comment, you just need to distinguish between strings and comments.

Here’s an example that might do this:

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

Using this in a replace function while replacing the matched string with the match of the first subpattern should then be able to remove the // style comments.

Some explanation:

  • [^/"']+ matches any character that is not the begin of a comment (both //… and /*…*/) or of a string
  • /\*(?:[^*]|\*+[^*/])*\*+/ matches the /* … */ style comments
  • "(?:[^"\\]|\\.)*" matches a string in double quotes
  • '(?:[^'\\]|\\.)*' matches a string in single quotes
  • \/\/.* finally matches the //… style comments.

As the first three constructs are grouped in a capturing group, the matched string is available and nothing is changed when replacing the matched string with the match of the first subpattern. Only if a //… style comment is matched the match of the first subpattern is empty and thus it’s replaced by an empty string.

But note that this may fail. I’m not quite sure if it works for any input.

这篇关于正则表达式,用于干净的JavaScript注释类型//的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆