I
I
Ivan Kurnakov2016-04-26 14:07:23
PostgreSQL
Ivan Kurnakov, 2016-04-26 14:07:23

How to get all characters before / using regular expressions?

In postgresql, there was a need to receive a string, or a part of a string before /, containing only numbers.
I've been struggling with the problem for a couple of hours now and can't solve it.
Lines can be of the form "1235", "1234/12", "dfhdhj1232", "dfhdhj1232/12"
From these lines I need to get
"1235", "1234", "not valid", "not valid" respectively.
In this example, everything works fine if / is present, when it is not, the expression returns null.

select substring('123405/99' from '#"%[0-9]#"/%' for '#')

When trying to use
select substring('123405/99' from '#"%[0-9]#"/?%' for '#')

will be 123405/99 , which surprises me, because I only get what is limited to #" characters.
I tried using (?=re), but also did not get the desired result.
select substring('123405/99' from '^(?=1)([0-9]{1,2})' for '#')

Please tell me the correct version of the expression and where am I wrong in trying to compose the correct expression?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
asd111, 2016-04-26
@Skinner2170

Try:

select regexp_matches('1235', '^(\d+)\/?');
select regexp_matches('1234/12', '^(\d+)\/?');
select regexp_matches('dfhdhj1232', '^(\d+)\/?');
select regexp_matches('dfhdhj1232/12', '^(\d+)\/?');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question