在"之前和之后获取子串。"完全停止,如果未找到则获取NULL

时间:2017-06-09 06:24:49

标签: sql oracle oracle11g

我希望在"之后和之前得到子字符串。",例如

Furniture.Chair 我需要" Category1"栏目和主席在"类别2"列,但如果字符串是这样的:

家具。然后我需要" Null" in" Category2"柱。但我无法做到这一点。 请参阅以下屏幕进行校正: enter image description here

由于

1 个答案:

答案 0 :(得分:0)

with data (val) as
(
  select 'furniture' from dual union all -- without the dot 
  select 'furniture.' from dual union all -- dot at the end
  select '.furniture' from dual union all -- dot at the beginning
  select null from dual union all -- no input
  select 'home owners.home.home' from dual union all -- if more than one dot is found
  select 'health and beauty.skin care' from dual -- words followed by dot followed by words
)
, coll as
(
select 
  val, 
  -- [^\.]+  any character sequence other than dot (+ is for one or more)
  -- (\.|) find a dot or nothing - eg. 'furniture' with a dot 
  -- (([^\.]+)) the outer brackets capture the first group \1; 
  --            the first inner brackets capture the second group
  --            the last argument to the regexp_substr below ie. '2' tells 
  --            method our interest is in the second group within the match 
  --            identified by (([^\.]+)(\.|)) 
  regexp_substr(val, '(([^\.]+)(\.|))', 1, 1, null, '2') as first,  
  regexp_substr(val, '(\.(.*))', 1, 1, null, '2') as the_rest 
from data
)
select 
  val, 
  case when first is null then 'Unknown Category' else first end as first,
  case when first is null then 'Unknown Category' else first end as the_rest
from coll
;