简体   繁体   中英

Regex replace character with index of match

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?

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 want a one line solution you could do something like, but could be slow for large strings as it has to find the count of the "?" for each match

 var result = Regex.Replace(input, @"\?", m => "@p" + input.Take(m.Index).Count(c => c == '?'));

Returns "book_id = @p0 and author_id = @p1 and publisher_id = @p2"

This is the only way I can see to get an indext without declaring an outside variable.

My solution with StringBuilder is not bad but isn't fastest nor most elegant :(

var count = 1;
var sb = new StringBuilder(input);
for (int i = 0; i < sb.Length; i++)
{
    if (sb[j] == '?')
    {
        sb.Remove(i, 1);
        sb.Insert(i, "@p" + (count++));
        i += 3;
    }
}
result = sb.ToString();

Untested:

int n, i=1; while( (n=input.IndexOf("?")) != -1) { input = input.Substring(0,n-1) + "@p" + (++i) + input.Substring(n+1); }

A longish line, but not completely unreasonable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM