You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何替换字符串内部单引号且保留首尾单引号?

替换字符串内部单引号(保留首尾单引号)

方法一:拆分拼接法

逻辑直观,分三步处理:

  1. 定位字符串中第一个和最后一个单引号的位置
  2. 提取首尾单引号之间的内容,将其中的单引号替换为双单引号
  3. 重新拼接首尾部分与替换后的中间内容

以C#为例,代码实现如下:

string myString = "'OA'Nel'Test, John; random's t'est'";

int firstQuote = myString.IndexOf('\'');
int lastQuote = myString.LastIndexOf('\'');

if (firstQuote != -1 && lastQuote != -1 && firstQuote < lastQuote)
{
    // 提取中间内容
    string middleContent = myString.Substring(firstQuote + 1, lastQuote - firstQuote - 1);
    // 替换中间的单引号
    string replacedMiddle = middleContent.Replace('\'', '\'\'');
    // 拼接结果
    string result = myString.Substring(0, firstQuote + 1) + replacedMiddle + myString.Substring(lastQuote);
    // 输出:"'OA''Nel''Test, John; random''s t''est'"
}

方法二:正则表达式替换法

利用正则匹配首尾单引号之间的内容,再对匹配到的内容进行单引号替换:

using System.Text.RegularExpressions;

string myString = "'OR'Nel, Dan' ";
string result = Regex.Replace(myString, @"(?<=')(.*?)(?=')", match => match.Value.Replace("'", "''"));
// 输出:"'OR''Nel, Dan' "

这里的正则(?<=')(.*?)(?=')会匹配被单引号包裹的中间内容,然后通过委托将匹配到的内容里的单引号替换为双单引号。

效果验证

针对输入示例:

  • 输入:myString = "'O'Nel'" → 输出:"'O''Nel'"
  • 输入:myString = "'OR'Nel, Dan' " → 输出:"'OR''Nel, Dan' "
  • 输入:myString = "'OA'Nel'Test, John; random's t'est'" → 输出:"'OA''Nel''Test, John; random''s t''est'"

内容的提问来源于stack exchange,提问作者Dave

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 13:50:03