我有一个要求,我需要删除字符串的一部分,如下所示:
string input = "SELECT ENTERPRISE_ID enterpriseId, ENTERPRISE_NAME enterpriseName, EMAIL email, DATEFORMATSTR dateFormatStr, TO_CHAR(DELETEDON,'HH:MI:SS AM') TIME, DELETEDON FROM LOG_FILE_DELETION_DATA WHERE AND COLNAME = '' AND";
应删除 WHERE 子句后第一次出现的 AND。我尝试了以下方法可以将其删除:
public static string RemoveWord(string str, int start, int end)
{
return str.Substring(0, start) + str.Substring(end, str.Length - end).Trim();
}
上面的问题是,当它通过查询检查上述字符串的长度时,长度是186。尽管长度不止于此。我不知道为什么会发生这种情况,但是有没有更好的方法可以消除 WHERE 子句之后第一次出现 AND ?
你可以使用正则表达式吗:
using System;
using System.Text.RegularExpressions;
class Program
{
public static void Main()
{
string input = "SELECT ENTERPRISE_ID enterpriseId, ENTERPRISE_NAME enterpriseName, EMAIL email, DATEFORMATSTR dateFormatStr, TO_CHAR(DELETEDON,'HH:MI:SS AM') TIME, DELETEDON FROM LOG_FILE_DELETION_DATA WHERE AND COLNAME = '' AND";
string result = RemoveFirstAndAfterWhere(input);
Console.WriteLine(result);
}
public static string RemoveFirstAndAfterWhere(string input)
{
string pattern = @"(WHERE\b.*?)\bAND\s*";
return Regex.Replace(input, pattern, "$1", RegexOptions.IgnoreCase);
}
}
输出:
SELECT ENTERPRISE_ID enterpriseId, ENTERPRISE_NAME enterpriseName, EMAIL email, DATEFORMATSTR dateFormatStr, TO_CHAR(DELETEDON,'HH:MI:SS AM') TIME, DELETEDON FROM LOG_FILE_DELETION_DATA WHERE COLNAME = '' AND