在我的输入文件中,我需要根据各种条件使用正则表达式进行大量字符串操作(查找/替换)。就像,如果内容的一个块满足条件,我需要转到上一个块并在该块中进行替换。
出于这个原因,我将内容拆分为许多子字符串,以便我可以回到上一个块(这里是上一个子字符串);并进行正则表达式替换。但是如果文件内容更多(或者可能是,子字符串的数量超过),程序会挂在中间。
这是代码片段。
string content = string.Empty;
string target_content = string.Empty;
string[] active_doc_nos;
byte[] content_bytes;
FileInfo input_fileinfo = new FileInfo(input_file);
long file_length = input_fileinfo.Length;
using (FileStream fs_read = new FileStream(input_file, FileMode.Open, FileAccess.Read))
{
content_bytes = new byte[Convert.ToInt32(file_length)];
fs_read.Read(content_bytes, 0, Convert.ToInt32(file_length));
fs_read.Close();
}
content = ASCIIEncoding.ASCII.GetString(content_bytes);
if (Regex.IsMatch(content, "<\\?CLG.MDFO ([^>]*) LEVEL=\"STRUCTURE\""))
{
#region Logic-1: TWO PAIRS of MDFO-MDFC-s one pair following the other
content = Regex.Replace(content, "(<\\?CLG.MDFO)([^>]*)(LEVEL=\"STRUCTURE\")", "<MDFO_VALIDATOR>$1$2$3");
string[] MDFO_Lines = Regex.Split(content, "<MDFO_VALIDATOR>");
active_doc_nos = new string[MDFO_Lines.GetLength(0)];
active_doc_nos[0] = Regex.Match(MDFO_Lines[0], "ACTIVE DOC=\"([^>]*)\"\\s+").ToString();
for (int i = 1; i < MDFO_Lines.GetLength(0); i++)
{
active_doc_nos[i] = Regex.Match(MDFO_Lines[i], "ACTIVE DOC=\"([^>]*)\"\\s+").ToString();
if (Regex.IsMatch(MDFO_Lines[i - 1], "(<\\?CLG.MDFC)([^>]*)(\\?>)(<\\S*\\s*\\S*>)*$"))
{
MDFO_Lines[i - 1] = Regex.Replace(MDFO_Lines[i - 1], "(<\\?CLG.MDFC)([^>]*)(\\?>)(<\\S*\\s*\\S*>)*$", "<?no_smark?>$1$2$3$4");
if (Regex.IsMatch(MDFO_Lines[i - 1], "^<\\?CLG.MDFO ([^>]*) ACTION=\"DELETED\""))
{
MDFO_Lines[i - 1] = Regex.Replace(MDFO_Lines[i - 1], "^<\\?CLG.MDFO ([^>]*) ACTION=\"DELETED\"", "<?no_bmark?><?CLG.MDFO $1 ACTION=\"DELETED\"");
}
if (active_doc_nos[i] == active_doc_nos[i - 1])
{
MDFO_Lines[i] = Regex.Replace(MDFO_Lines[i], "^<\\?CLG.MDFO ([^>]*) " + active_doc_nos[i], "<?no_smark?><?CLG.MDFO $1 " + active_doc_nos[i]);
}
}
}
foreach (string str_piece in MDFO_Lines)
{
target_content += str_piece;
}
byte[] target_bytes = ASCIIEncoding.ASCII.GetBytes(target_content);
using (FileStream fs_write = new FileStream(input_file, FileMode.Create, FileAccess.Write))
{
fs_write.Write(target_bytes, 0, target_bytes.Length);
fs_write.Close();
}
我还有其他选择来完成这项任务吗?