regex to replace backslash and single quote with single quote using postgres regexp_replace()
Asked Answered
D

2

7

Just as the title states, I'm not the best w/ regex, so can anyone provide the appropriate regex for the following:

UPDATE table SET column = REGEXP_REPLACE(column, {regex}, '''');

Basically, I'd like to replace any instances of backslashes (\) followed by one or more single quotes with one single quote.

So, the string Hello World\'s or Hello World\'''''s should become Hello World's, but not Hello World\s.

Drucilladrucy answered 14/1, 2015 at 18:4 Comment(0)
P
10

This is relatively straightforward. Note that both the backslash character \ as well as the single-quote character ' (which you escaped in the OP) need to be escaped. The difference is that the backslash has to be escaped in the regex itself, whereas the single quote is escaped in the string literal. Anyway, enough of that digression.

UPDATE table SET column = REGEXP_REPLACE(column, '\\''+', '''', 'g');

Hope this helps.

Prothorax answered 14/1, 2015 at 18:39 Comment(1)
I ended up using this and accepted, I appreciate the explanation as well.Drucilladrucy
N
3

You can try the following:

SELECT REGEXP_REPLACE(column, '\\''['']*', '''','g') from table

Edit: of course \''+ is better

SELECT REGEXP_REPLACE(column, '\\''+', '''','g') from table
Noma answered 14/1, 2015 at 18:12 Comment(2)
and why not '\\''+' ?Church
can single quote be escaped by another single quote '^''*$'Echolocation

© 2022 - 2024 — McMap. All rights reserved.