![](/img/trans.png)
[英]Regular expression that excludes carriage return returns a match with carriage return
[英]Regular Expression to eliminate unwanted carriage returns is too slow in the C# script task
我有一个带注释列的.csv文件。 该列包含某些行的回车符和换行符。 因此,加载过程失败(正在通过SSIS程序包加载)。 我添加了一个脚本任务,以从文件中删除不需要的回车符和换行符(在每行的末尾保留一个)。
我正在使用下面的代码来做到这一点。 我面临的问题是,使用小文件可以正常运行代码,但对于大文件则需要花费太长时间(37k记录的时间超过了1小时,并附带示例文件中显示的结构)。
我对C#脚本非常陌生,因此无法优化脚本任务中使用的正则表达式。 有没有更好的方式编写正则表达式,以便使其运行得更快?
使用的代码:
string myFileData;
string FilePath = Dts.Variables["FilePath"].Value.ToString(); //source file path
string DestinationFilePath = Dts.Variables["DestinationFilePath"].Value.ToString(); //destination file path
const string delimeters = @"\s(?!(([^""]*""){2})*[^""]*$)"; //string pattern to be used in regular expression
myFileData = File.ReadAllText(FilePath);
if (Regex.IsMatch(myFileData, delimeters))
{
File.WriteAllText(DestinationFilePath, Regex.Replace(myFileData, delimeters, " "));
}
样本数据:
Seminar,Seminar Date,Location,First name,Last name,Comments
Test Seminar,13/10/2014,Sydney,TEST1_FN,TEST1_LN,This is Test1
Test Seminar,13/10/2014,Sydney,TEST2_FN,TEST2_LN,This is Test2
Test Seminar,13/10/2014,Sydney,TEST3_FN,TEST3_LN,This is Test3
Test Seminar,13/10/2014,Sydney,TEST4_FN,TEST4_LN,"This
is
Test4"
Test Seminar,13/10/2014,Sydney,TEST5_FN,TEST5_LN,This is Test5
声明您的正则表达式广告字段并设置“已编译”选项:
_regex = new Regex(@"\s(?!(([^""]*""){2})*[^""]*$)", RegexOptions.Compiled);
并使用它:
_regex.Replace(myFileData, " ");
会更快一点。 另外,在替换之前不要检查-删除if
语句,因为Replace
也可以。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.