AliReza Tavakoliyan
AliReza Tavakoliyan

Reputation: 31

how to get characters between [ ] in postgresql

I want get characters between [] from a string

example:

"hello" and "world"

from

"gegerferf[hello] frfer [world] frfre rfrf"

into a table

i am try with substring and for loop but i dont now.

select regexp_replace(string, '...','', 'g')
from mytable

Upvotes: 1

Views: 51

Answers (2)

jian
jian

Reputation: 4877

SELECT  (REGEXP_MATCHES('gegerferf[hello] frfer [world] frfre rfrf','(?:\[)(.*?)(?:\])','g'))[1];

Upvotes: 1

JohnH
JohnH

Reputation: 3190

The question didn't provide an example of the expected results, so I'll present a couple of options.

The following is run to setup the demonstration context:

CREATE TABLE t (
  id serial primary key,
  string text
);

INSERT INTO t(string)
VALUES ('gegerferf[hello] frfer [world] frfre rfrf');

This query returns the text between brackets concatenated into a single string:

SELECT regexp_replace(string, '[^[]*\[([^]]*)\][^[]*', '\1', 'g')
  FROM t;

The result is:

 regexp_replace 
----------------
 helloworld
(1 row)

This query returns the text between brackets as separate rows:

SELECT (regexp_matches(string, '\[([^]]*)\]', 'g'))[1]
  FROM t;

The output is:

 regexp_matches 
----------------
 hello
 world
(2 rows)

Upvotes: 1

Related Questions