c# - 正则表达式用匹配索引替换字符

标签 c# regex replace

我需要取这个字符串:

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/

相关文章:

regex - 如何从宏中提取唯一字符串?

.net - 如何从 WHOIS 结果中解析电子邮件地址

string - 如何在golang中替换字符串中的所有字符

用 R 中的相应替换字符串替换一组模式匹配

Python 使用索引和/或值替换值

c# - 检查代码是否从 Windows 窗体应用程序调用

regex - 如何查找名称中带方括号的文件

c# - 针对整个模式验证单个 XML 节点

c# - DropNet 无法保存后续请求的访问 token ?

C#如何使用Uri equal?