繁体   English   中英

如何用C#中的某些字符替换具有单引号的字符串

[英]how to replace a string having single quote with some characters in C#

我需要一个代码来搜索字符串是否在字符前包含单引号' ,并且该单引号应替换为两个单引号' '

例-:

input = "test's"
output = "test''s"

input = "test'"
output = "test'"

input = "test' "
output = "test' "

使用正向前瞻检查下一个字符是否为单词:

string input = "test's";
var result = Regex.Replace(input, @"'(?=\w)", @"""");

此代码使用正则表达式将输入字符串中的匹配项替换为双引号。 要匹配的模式是'(?=\\w) 它包含单引号和下一个字符的正向查找(字符本身将不包含在匹配项中)。 如果找到匹配项(即输入包含单引号和单词字符,则用给定的字符串替换引号(在这种情况下为双引号)。

更新:编辑和注释后,正确的替换应如下所示

var result = Regex.Replace(input, "'(?=[a-zA-Z])", "''");

输入:

"test's"
"test'"
"test' "
"test'42"
"Mr Jones' test isn't good - it's bad"

输出:

"test''s"
"test'"
"test' "
"test'42"
"Mr Jones' test isn''t good - it''s bad"

尝试这种方式

    String input = input.Replace("'","\"");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM