简体   繁体   English

我们可以使用C#比较两个JavaScript文件吗?

[英]Can we compare two JavaScript files using C#?

I have tried comparing two text files. 我尝试比较两个文本文件。 If these contain the same data but there is a difference of even one space the result is showing as 'different'. 如果这些数据包含相同的数据,但即使只有一个空格也存在差异,则结果将显示为“不同”。

Can anyone tell me how to compare two JavaScript files using C#? 谁能告诉我如何使用C#比较两个JavaScript文件?

Since JavaScript is whitespace tolerant (tolerates any amount of whitespace as long as the syntax is correct), the simplest thing to do if you want to compare everything but the whitespace is to regex-replace: 由于JavaScript是空白宽容(只要语法正确容忍空白的任何金额),如果你想要,但空格是正则表达式替换比较一切简单的事:

Regex _r = new Regex(@"\s+", RegexOptions.Compiled);
string result = _r.Replace(value, " ");

Run this on both files and compare the results; 在两个文件上都运行此程序并比较结果; it replaces any sequence of standard whitespace characters (space, tab, carriage return, vertical tab etc.) with a single space. 它用单个空格替换任何标准空格字符序列(空格,制表符,回车符,垂直制表符等)。 You can then compare with Equals (case sensitive or not, as you require). 然后,您可以与Equals进行比较(根据需要区分大小写)。

Of course, whitespace IS significant inside strings, so this assumes the string handling in all the compared files does not rely on whitespace too much. 当然,空格在字符串内部很重要,因此,这假定所有比较文件中的字符串处理都不过多地依赖空格。

However two very different code files can have the same effects, so if that's what you're after you have a hard job ahead of you. 但是,两个非常不同的代码文件可能具有相同的效果,所以如果这就是您在艰苦的工作之后要做的事情。

Do you just need to know if they are exactly the same? 您是否只需要知道它们是否完全相同? If so you could just load them into memory and compare the .length() property... 如果是这样,您可以将它们加载到内存中并比较.length()属性...

Technically, if one file contains an extra space they aren't "the same". 从技术上讲,如果一个文件包含多余的空间,则它们不是“相同”的。 I would first compare the lengths and if those don't match you'll need to do a byte by byte comparison. 我首先要比较长度,如果长度不匹配,则需要逐字节比较。 If you want to remove extra spaces you'll probably want to do something like a Trim() on the contents of both files first. 如果要删除多余的空间,则可能需要先对两个文件的内容执行类似Trim()的操作。

Here's a link to an old MS post describing how to create a file compare function: 这是旧MS帖子的链接,描述了如何创建文件比较功能:

http://support.microsoft.com/kb/320348 http://support.microsoft.com/kb/320348

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM