简体   繁体   中英

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

I need a code which will search if a string contains single quote ' before a character and that single quote should be replaced with two single quotes ' ' .

example-:

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

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

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

Use positive lookahead to check if next character is a word:

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

This code uses regular expression to replace match in input string with double quotes. Pattern to match is '(?=\\w) . It contains single quote and positive lookahead of next character (character itself will not be included in match). If match is found (ie input contains single quote followed by word character, then quote is replaced with given string (double quote in this case).

UPDATE: After your edit and comments, correct replacement should look like

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

Inputs:

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

Outputs:

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

尝试这种方式

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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