您的位置:首页 > 数据库

[原]Sql脚本压缩类。

2015-07-07 15:56 369 查看
精简的美丽

/*
* Sql脚本压缩类。
* 去掉sql语句中多余的空格,以减少sql脚本的文本长度
*
* Author   : goldli@163.com
* DateTime : 2015/07/03
*/

using System.Text.RegularExpressions;

namespace Sp.Net.Tools
{
internal class SqlCompressor
{
public static string Compress(string source)
{
if (string.IsNullOrEmpty(source)) return "无数据";
//1.去掉所有注释; 行注释 与 块注释
source = LineComment(source);
source = BlockComment(source);
//2.压缩空格
source = MultipleSpace(source);
//3.压缩标点符号
source = Punctuates(source);
return source;
}

/// <summary>
/// 去掉行注释
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
private static string LineComment(string source)
{
//去掉 "--" 开头的行
var x = Regex.Replace(source, "--.*", "", RegexOptions.IgnoreCase | RegexOptions.Multiline);

return x;
}

private static string BlockComment(string source)
{
//去掉 "/* */" 的行
var x = Regex.Replace(source,@"\/\*.*\*\/","",RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline);

return x;
}

private static string MultipleSpace(string source)
{
var x = Regex.Replace(source,@"\s{2,}"," ",RegexOptions.IgnoreCase | RegexOptions.Multiline);

return x;
}

/// <summary>
/// 空格在标点符号的两侧
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
private static string Punctuates(string source)
{
var x = Regex.Replace(source,@"\s*([\)\(\,\;\.\:\'\""\=\+\-\*\/\>\<\!\|\~\^])\s*","$1",RegexOptions.IgnoreCase | RegexOptions.Multiline);

return x;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: