user3682903
user3682903

Reputation: 49

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' "

Upvotes: 0

Views: 1735

Answers (2)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236188

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 (i.e. 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"

Upvotes: 2

Hiral Nayak
Hiral Nayak

Reputation: 1072

try this way

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

Upvotes: 0

Related Questions