Skip to Main Content
  • Questions
  • How can I get characters before and after '-OO' character in a sentence?

Breadcrumb

Question and Answer

Connor McDonald

Thanks for the question, Derek.

Asked: October 13, 2018 - 12:26 pm UTC

Last updated: October 16, 2018 - 2:04 am UTC

Version: 12

Viewed 1000+ times

You Asked

Hi Tom,

I have a string like '000-O 1000 DENIS GRATTON TRANSPORT LTD-OO Profile Class-PHONE-25183', can I use oracle regular expression to get all characters before '-OO'? I am using Oracle 12c release 1

Kind Regards,

Derek

and Connor said...

SQL> with t as (
  2  select '000-O 1000 DENIS GRATTON TRANSPORT LTD-OO Profile Class-PHONE-25183' x from dual )
  3  select
  4    regexp_substr(x,'(.*)-OO',1,1,'i',1) from t;

REGEXP_SUBSTR(X,'(.*)-OO',1,1,'I',1)
--------------------------------------
000-O 1000 DENIS GRATTON TRANSPORT LTD


the last '1' parameter is "Get me the first nominated subsection" where subsection was defined by the brackets.

Rating

  (2 ratings)

Is this answer out of date? If it is, please let us know via a Comment

Comments

Can I get after -OO all characters?

Derek Xu, October 15, 2018 - 2:20 am UTC

Hi Tom,

Thank you very much for your support, another question can I get after -OO all characters?

And how can I get all characters after first '-' and before -OO all characters?

Kind Regards,

Derek

But why?

AndyP, October 15, 2018 - 7:13 am UTC

I feel like I've turned into the "unnecessary use of regexp" police, but why not just do this?
with data as
(
select '000-O 1000 DENIS GRATTON TRANSPORT LTD-OO Profile Class-PHONE-25183' x
  from dual
)
select x
      ,instr(x,'-OO')
      ,substr(x,1,instr(x,'-OO')-1) before
      ,substr(x,instr(x,'-OO')+3,length(x)) after
  from data;

X                                                                   INSTR(X,'-OO')
------------------------------------------------------------------- --------------
BEFORE
-------------------------------------------------------------------
AFTER
-------------------------------------------------------------------
000-O 1000 DENIS GRATTON TRANSPORT LTD-OO Profile Class-PHONE-25183             39
000-O 1000 DENIS GRATTON TRANSPORT LTD
 Profile Class-PHONE-25183

Connor McDonald
October 16, 2018 - 2:04 am UTC

As we say in Australia, there is more than one way to skin a cat.

More to Explore

PL/SQL demos

Check out more PL/SQL tutorials on our LiveSQL tool.

PL/SQL docs

PL/SQL reference manual from the Oracle documentation library