[原]Sql脚本压缩类。

时间:2023-12-01 15:48:38

精简的美丽

/*
* 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;
}
}
}