正则表达式来删除JavaScript的双斜杠(//)风格的注释 [英] Regex to remove javascript double slash (//) style comments

查看:336
本文介绍了正则表达式来删除JavaScript的双斜杠(//)风格的注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做去除通过正则表达式JavaScript注释在C#中,并已成为卡住了。我想删除双斜线的任何事件// 样式的注释。

I'm trying to do remove javascript comments via regex in C# and have become stuck. I want to remove any occurrences of double slash // style comments.

我目前的正则表达式是(小于:?!)// [^ \ r \ n]的* 将捕获所有的意见和prevent匹配的http:// 。然而,消极的后向懒惰,当然咬了我回到了下面的测试案例:

My current regex is (?<!:)//[^\r\n]* which will catch all comments and prevent matching of http://. However, the negative lookbehind was lazy and of course bit me back in the following test case:

var XSLPath = "//" + Node;

所以,我在找一个正规的前pression将进行回顾后,看是否在比赛前出现偶数的双引号() 。我不知道这是可能的。或者,也许有更好的方法来做到这一点?

So I'm looking for a regular expression that will perform a lookbehind to see if an even number of double quotes (") occurs before the match. I'm not sure if this is possible. Or maybe there's a better way to do this?

推荐答案

(更新基于评论)

它看起来像这样的作品pretty的还有:

It looks like this works pretty well:

(?<=".*".*)//.*$|(?<!".*)//.*$

目前看来,在正则表达式英雄的测试用例表明它会匹配的意见,我认为它应该的方式(几乎)。

It appears that the test cases in Regex Hero show that it'll match comments the way I think it should (almost).

例如,它会完全忽略这一行:

For instance, it'll completely ignore this line:

var XSLPath = "//" + Node;

但它是足够聪明,以匹配注释这行的末尾:

But it's smart enough to match the comment at the end of this line:

var XSLPath = "//"; // stuff to remove

不过,它不是足够聪明,知道如何处理的意见前3个或更多引号。我不完全知道如何解决这个问题没有硬编码。你需要一些方法来使偶数引号。

However, it's not smart enough to know how to deal with 3 or more quotation marks before the comment. I'm not entirely sure how to solve that problem without hard-coding it. You need some way to allow an even number of quotes.

这篇关于正则表达式来删除JavaScript的双斜杠(//)风格的注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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