Reputation: 59
I am attempting to insert a date into an SQL query string so that I don't have to keep modifying two different SQL files.
I thought I could just look for the Start Date that I declare in my SQL Query and replace the date that is set there currently. So I have a regex that captures the date that is currently there and want to replace it with a new date.
SQL
DECLARE @StartDate DATE = '2014-06-06'
DECLARE @EndDate DATE = '2015-07-18'
C#
DateTime startDate = new DateTime(2018,06,06);
string PerformanceQuery = File.ReadAllText("<PathtoSql>");
Regex startDateReplace = new Regex("StartDate DATE = '(.*?)'");
string newPerformanceQuery = startDateReplace.Replace(PerformanceQuery, $"1" + startDate.ToString("yyyy-MM-dd")");
Expected:
DECLARE @StartDate DATE = '2018-06-06'
DECLARE @EndDate DATE = '2015-07-18'
Actual:
DECLARE @12018-06-06
DECLARE @EndDate DATE = '2015-07-18'
Upvotes: 0
Views: 90
Reputation: 14038
Capture the pieces you want to remain unchanged and include them in the replacement.
Regex startDateReplace = new Regex("(StartDate DATE = ').*?(')");
string newPerformanceQuery = startDateReplace.Replace(PerformanceQuery,
"${1}" + startDate.ToString("yyyy-MM-dd")" + "$2");
Note the ${1}
in the replacement string. This is because the new date string starts with a digit and, without the ${1}
the replacement looks like $12018-
which asks for the (non-existant) capture number 12018.
You could simplify the above in this case by recognising that both the capture groups have fixed content, and rewrite them as below. I generally prefer to use the captures as it makes it clear that the text is not changed, it reduces the opportunity for errors if the search strings change (and only one copy is modified), and it works for cases when the strings are not fixed.
Regex startDateReplace = new Regex("StartDate DATE = '.*?'");
string newPerformanceQuery = startDateReplace.Replace(PerformanceQuery,
"StartDate DATE = '" + startDate.ToString("yyyy-MM-dd")" + "'");
Upvotes: 1
Reputation: 37337
Just use positive lookbehind: (?<=StartDate DATE = ')[^']*?
Upvotes: 1