Regex replace character with compliance index

I need to take this line:

book_id = ? and author_id = ? and publisher_id = ? 

and turn it into this line:

 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 a group index?

+4
source share
4 answers

You can use the Regex.Replace method, which 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 => is a MatchEvaluator . In this case, there is no need to use Match (which is equal to m ); we just want to return the concatenated result and increase the counter.

+2
source

Unverified:

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

A long line, but not entirely unfounded.

0
source

If you want to use a single line solution, you can do something like this, but it can be slow for large lines, since it has to find the counter ?? for every 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 to see indext without declaring an external variable.

0
source

I am writing a project to check other answers and my own. You can get it here .
Output:
- The linq solution is the fastest.
- The Regex solution is the most elegant.
- My solution with StringBuilder is not bad, but not fast and not elegant :(

Here is my solution:

 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(); 
0
source

All Articles