1

I have to find the first sequence of four numbers inside a table using Oracle SQL.

Inside the input_file_name column we can find values as:

RVSP_040517.M
SERIES_040517_CP.TXT
SAUDE_O10N0505.M
SERIES_040517.txt
RVSP_080517.M
SERIES_080517_CP.TXT

As we can see, there is groups of numbers before, but the first group of four numbers from the left is what I want. I want to create a new column with this day-mouth (4) numbers.

How can I do it?

The result I am expecting from this table is:

0405
0405
0505
0405
0805
0805

I was trying to use inStr but it wasn't working

1 Answer 1

2
select ..., regexp_substr(input_file_name, '\d{4}') as day_month, ...
from   ...

Demo (with a few more strings to show what happens when there aren't any substrings of four consecutive digits, or more than one occurrence of such substrings):

with
     test_data ( input_file_name ) as (
       select 'RVSP_040517.M'        from dual union all
       select 'SERIES_040517_CP.TXT' from dual union all
       select 'SAUDE_O10N0505.M'     from dual union all
       select 'SERIES_040517.txt'    from dual union all
       select 'RVSP_080517.M'        from dual union all
       select 'SERIES_080517_CP.TXT' from dual union all
       select 'mathguy wins'         from dual union all
       select 'GOOD_031.pdf'         from dual union all
       select 'FOUR_DIGITS_123_4'    from dual union all
       select 'A22409_11230.cpp'     from dual
     )
-- End of simulated data (for testing purposes only, not part of the solution).
-- SQL query begins BELOW THIS LINE.
select input_file_name, regexp_substr(input_file_name, '\d{4}') as day_month
from   test_data
;

INPUT_FILE_NAME       DAY_MONTH          
--------------------  ------------
RVSP_040517.M         0405                
SERIES_040517_CP.TXT  0405                
SAUDE_O10N0505.M      0505                
SERIES_040517.txt     0405                
RVSP_080517.M         0805                
SERIES_080517_CP.TXT  0805                
mathguy wins                             
GOOD_031.pdf                             
FOUR_DIGITS_123_4
A22409_11230.cpp      2240
Sign up to request clarification or add additional context in comments.

Comments

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.