Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex replace character with index of match

Tags:

c#

regex

replace

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?

like image 570
schmij Avatar asked Mar 05 '13 00:03

schmij


People also ask

What is $1 in regex replace?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.

What does .*)$ Mean?

*$ 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.


1 Answers

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.

like image 87
Ahmad Mageed Avatar answered Oct 14 '22 18:10

Ahmad Mageed