4

I have query to remove double space and convert it to single space.

UPDATE tablename SET name=trim(regexp_replace(name,'\s\s+',' ', 'g'));

It gives error:

WARNING: nonstandard use of escape in a string literal
HINT:  Use the escape string syntax for escapes, e.g., E'\r\n'.
Erwin Brandstetter
  • 539,169
  • 125
  • 977
  • 1,137
Dhairya Lakhera
  • 3,932
  • 3
  • 27
  • 47

2 Answers2

4

You are running an old version of Postgres with the setting escape_string_warning = on (default) and standard_conforming_strings = off (outdated!, default is on since Postgres 9.1). The manual:

escape_string_warning(boolean)

When on, a warning is issued if a backslash (\) appears in an ordinary string literal ('...' syntax) and standard_conforming_strings is off. The default is on. (...)

To just fix the syntax and get rid of the WARNING:

trim(regexp_replace(name, E'\\s\\s+', ' ', 'g'))

Proper solution: Upgrade to a current version of Postgres, or fix the outdated setting to standard_conforming_strings =on.
In modern Postgres, the expression you have is valid as is.

To be precise, \s is the class shorthand for [[:space:]], which includes any kind of white space (incl. tab, nbsp etc.). Your expression replaces any string of two or more white space char with a single space char. The expression to fit your description would be:

trim(regexp_replace(name,'  +', ' ', 'g'))

... which works regardless of version and above settings.

Related:

Community
  • 1
  • 1
Erwin Brandstetter
  • 539,169
  • 125
  • 977
  • 1,137
  • If using PHP you can use pg_escape_literal (NOT pg_escape_string) which will delimit and escape your strings correctly according to your postgres settings. http://php.net/manual/en/function.pg-escape-literal.php – Pascal_dher May 28 '18 at 07:33
0

The below should also work.

trim(regexp_replace(name,E'\s+','\s{2}',
Muhammad Dyas Yaskur
  • 5,382
  • 10
  • 37
  • 61
  • Please have a read of the [formatting help page](https://stackoverflow.com/editing-help) to improve the formatting in your answer, and also check out [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer) to improve your answer. – costaparas Feb 16 '21 at 05:36