用于替换特定匹配项的字符串的第一个和最后一个字符的正则表达式

RegEx to replace the first and last character of string for a particular match

像这样。

句子是

string ttt = "This is ?chef? and ?teacher? time";

这句话应该改成

ttt = "This is 'chef' and 'teacher' time";

我在看一些在线样本 Regex.Replace(ttt, @"\?([^$]*)\?", "REPLACE"); 但我无法弄清楚我应该写什么来代替 REPLACE 。应该是按字计算的。

请帮我解决这个问题。

您将在替换调用中引用捕获组。这叫做反向引用。

String ttt = "This is ?chef? and ?teacher? time";
String result = Regex.Replace(ttt, @"\?([^?]*)\?", "''");
Console.WriteLine(result); //=> "This is 'chef' and 'teacher' time"

Back-references recall what was matched by a capture group( ... )。反向引用指定为 ($);后跟一个数字 表示要调用的组 的编号。

注意: 我使用 [^?] 作为否定,而不是匹配除文字 $ 以外的所有内容。


但如果您只想替换 ?,一个简单的替换就足够了:

String result = ttt.Replace("?", "'");