5

I have a table and want update query to update dob

------------
dob
------------
19101984
19111984
19071985
19081985
19101985
19121985

I want to remove sub string from position 5 to character length of 2 means in the result table will be :

------------
dob
------------
191084
191184
190785
190885
191085
191285

1 Answer 1

5

Use regex_replace:

select regexp_replace(dob::text, '(\d{4})\d{2}(\d{2})', E'\\1\\2')
from your_table;

For updating:

update your_table
set dob = regexp_replace(dob, '(\d{4})\d{2}(\d{2})', E'\\1\\2');

The regex pattern being used here is:

(\d{4})\d{2}(\d{2})
 ^^^^        ^^^^     <-- capture groups

The first four and last two digits are captured in groups 1 and 2, respectively. Then, we simply replace with the first and second capture group.

It is not clear whether the dob column is text or not. If it is numeric, then you should be able to cast to text and run the above query.

enter image description here

Demo

Sign up to request clarification or add additional context in comments.

8 Comments

Thanks for your effort. i have edited my question. i want update query
@Curious I updated my answer, but a lingering fear is that your dob column is numeric. If so, then to update as you want you would need to do a double cast. I won't update my answer further unless you tell us this is the case. In any event, I would argue that column should really be text anyway.
my dob field is character varying
its giving error WARNING: nonstandard use of escape in a string literal LINE 2: set dob1= regexp_replace(dob1, '(\d{4})\d{2}(\d{2})', E'\\1\... ^ HINT: Use the escape string syntax for escapes, e.g., E'\r\n'
@Curious Try using this: regexp_replace(dob, '(\d{4})\d{2}(\d{2})', E'\1\2') ... i.e. single backslashes for the capture groups. I simply used the Postgres documentation as a pattern for my answer, I'm surprised there are warning at all.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.