Home > OS >  Unexpected error when trying to parse string
Unexpected error when trying to parse string

Time:09-28

I have this table in PostgreSQL:

Table_T:

id body
1 bla bla bla Call ID: xxx Interaction ID: vvv bla bla
2 bla bla bla Call ID: zzz Interaction ID: ooo bla bla

This is the output I am expecting:

id Call_id
1 xxx
2 zzz

This the code I am using:

SELECT id
     , substring(body from position('Call ID:' in body) 8 for position('Interaction ID:' in body)- position('Call ID:' in body) 8)
FROM Table_T

I get this error:

Syntax error: Expected "(" or keyword UNNEST but got identifier at

Some documentation I reviewed:

What am I missing?

CodePudding user response:

The error message seems unrelated. The expression works for me. Except that you seem to have your calculation wrong. And it can be done much simpler with substring() and a regular expression:

SELECT id
     , substring(body FROM position('Call ID:' in body)   9 FOR position('Interaction ID:' in body) - position('Call ID:' in body) - 10) AS proper
     , substring(body, 'Call ID: (.*) Interaction ID:') AS better
FROM   table_t;

fiddle

CodePudding user response:

You can use regexp_match:

select id, (regexp_match(body, '(?<=ID\:\s)\w '))[1] Call_id from Table_T

See fiddle.

  • Related