Bash
使用 regexp_replace 替換字元串周圍的單引號,但不能替換單詞中的單引號,例如不能
我正在使用 bash 腳本中的以下程式碼將 postgres 數據庫中標題列中的單引號替換為空格。
psql -U postgres -d my_database -c "UPDATE my_table SET title = regexp_replace(title, '''', ' ', 'g')"
我的問題是我打算刪除字元串周圍的單引號,例如,像這樣:
this is example 'number one' ok
變成
this is example number one ok
這正如我所希望的那樣工作。但是,它也從單詞中刪除了單引號,所以:
can't
變成
can t
如何指定我只想替換字元串周圍的單引號。
我認為只有一個替代品沒有什麼好的方法。但是,如果四個替換都可以,請執行以下操作:
- 替換
\A'
為(that is, replace
’at the beginning of the string).
- Replace
’\Zby
(that is, replace'
at the end of the string).- Globally replace
([^[:alnum:]])'
by\1
(that is, replace every sequence of a non-alphanumeric character and'
by the non-alphanumeric character and).
- Globally replace
’([^[:alnum:]])by
\1(that is, replace every sequence of
’and a non-alphanumeric character by
and the non-alphanumeric character.)```` ```The net effect is to replace every'
, except those that are preceded and followed by an alphanumeric character.Disclaimer: I have no clue about PostgreSQL; you have to translate it into PostgreSQL syntax yourself.```