Reputation: 4511
I have word ST.JOHN'S
If I run this two times(for argument sake, I have a legit reason):
String.Replace("'", "''")
the result will be ST.JOHN''''S
How can I replace '
Single quote with ''
two single quotes only when the '
single quote is without any additional '
single quotes around?
Upvotes: 2
Views: 534
Reputation: 24078
You can use a regex to assert that the quote is all by itself.
System.Text.RegularExpressions.Regex.Replace(inputText, "(?<!')'(?!')", "''")
Result:
System.Text.RegularExpressions.Regex.Replace("ST.JOHN'S", "(?<!')'(?!')", "''")
// ST.JOHN''S
System.Text.RegularExpressions.Regex.Replace("ST.JOHN''S", "(?<!')'(?!')", "''")
// ST.JOHN''S
Upvotes: 2
Reputation: 148980
You can use a regular expression, like this:
Regex.Replace("ST.JOHN'S", "([^']|^)'([^']|$)", "$1''$2") // ST.JOHN''S
Or like this:
Regex.Replace("ST.JOHN'S", "(?<!')'(?!')", "''") // ST.JOHN''S
Either way, this will only replace single '
characters not surrounded by any other '
characters.
Upvotes: 5