我需要取这个字符串:
book_id = ? and author_id = ? and publisher_id = ?
然后把它变成这个字符串:
book_id = @p1 and author_id = @p2 and publisher_id = @p3
使用此代码:
Regex.Replace(input, @"(\?)", "@p **(index of group)**");
给我组索引的替换模式是什么?
最佳答案
您可以使用 Regex.Replace
method它需要一个 MatchEvaluator
以及一个计数器变量:
string input = "book_id = ? and author_id = ? and publisher_id = ?";
string pattern = @"\?";
int count = 1;
string result = Regex.Replace(input, pattern, m => "@p" + count++);
m =>
部分是 MatchEvaluator
。在这种情况下,无需使用 Match
(即 m
);我们只想返回连接的结果并增加计数器。
关于c# - 正则表达式用匹配索引替换字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15213714/