Reputation: 49
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
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