[英]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.