I need to take this string:
book_id = ? and author_id = ? and publisher_id = ?
and turn it into this string:
book_id = @p1 and author_id = @p2 and publisher_id = @p3
using this code:
Regex.Replace(input, @"(\?)", "@p **(index of group)**");
What is the replacement pattern to give me the index of the group?
For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.
*$ means - match, from beginning to end, any character that appears zero or more times. Basically, that means - match everything from start to end of the string.
You could use the Regex.Replace
method that takes a MatchEvaluator
, along with a counter variable:
string input = "book_id = ? and author_id = ? and publisher_id = ?";
string pattern = @"\?";
int count = 1;
string result = Regex.Replace(input, pattern, m => "@p" + count++);
The m =>
part is the MatchEvaluator
. In this case there's no need to use the Match
(which is m
); we just want to return the concatenated result and increment the counter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With