Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a single quote character with two single quote characters

I want to replace all instances of a string quote (') with two single quotes ('') in a string.

Lets say e'QmfgLu/]sf]/sd is a string and I want to replace ' with ''.

The result must be e''OmfgLu/]

I tried this query:

update customer set name=REGEXP_REPLACE(name, E'\'', '''');

also

 update customer set name=REPLACE(name, E'\'', '''');

This query is not properly working. What is the suitable way to write the query?

like image 631
Mani Ratna Avatar asked Oct 21 '25 19:10

Mani Ratna


2 Answers

You may replace a single occurrence of single quotes with 2 quotes using this regexp.

update customer set name=REGEXP_REPLACE(name, $$([^'])'([^'])$$, $$\1''\2$$ ,'g');

$$([^'])'([^'])$$ - represents a sequence of any character other than a single quote followed by a quote and then a non-quote character.

I'm using the dollar quoting to avoid confusing quotes.

Demo

EDIT

As @edruid pointed out, to handle case for quotes at the start and end of string, use: REGEXP_REPLACE(name, $$([^']|^)'(?!')$$, $$\1''$$ ,'g')

This uses a negative lookahead for matching a single quote - (?!')

Demo2

like image 122
Kaushik Nayak Avatar answered Oct 23 '25 10:10

Kaushik Nayak


In postgres the way to have a single quote in a string is to type '' (' is used as the escape character) so your replace would be

update customer set name=REGEXP_REPLACE(name, E'''', '''''', 'g');

(skip the final 'g' if you only want to replace the first ')

or without resorting to regexp:

update customer set name=REPLACE(name, '''', '''''');
like image 27
edruid Avatar answered Oct 23 '25 10:10

edruid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!