从Oracle中给定的字符串中提取特定的字符串

时间:2019-03-13 09:58:48

标签: sql oracle

表达式-BR65437812-909@-@BR12340000-990

需要提取给定的表达式并更新列,例如 a = BR12340000b = 990

3 个答案:

答案 0 :(得分:1)

select 
  SUBSTR(s, 1, INSTR(s, '-') - 1) as a, 
  SUBSTR(s, INSTR(s, '-', -1) + 1) as b 
from 
  (select 'BR65437812-909@-@BR12340000-990' as s from dual)

使用SUBSTR(string, start, length),我们有以下参数:

对于A:

  • 要搜索的字符串
  • 1作为start
  • (index_of_the_first_hyphen-1)作为lengthINSTR(string, searchfor)给我们第一个连字符的索引

对于B:

使用SUBSTR(string, start),我们有参数:

  • 要搜索的字符串
  • (index_of_last_hyphen + 1)-这次我们使用额外的INSTR(string, searchfor, startindex)自变量startindex并将其设置为-1;这使得它从字符串的末尾开始搜索并向后工作,从而为我们提供了最后一个连字符的索引

我们不需要长度参数-没有长度的SUBSTR会将字符串的其余部分返回到结尾

重要的是要注意,起始索引为-1的INSTR确实向后搜索,但是它总是从字符串的开头而不是结尾返回索引。

INSTR('dddde', 'd', -1)  
       12345            -- returns 4, because d is 4 from the start
       54321            -- it does not return 2, even though d is 2 from the "start" when searching backwards

答案 1 :(得分:0)

with s as (
select 'BR65437812-909@-@BR12340000-990' str from dual)
select regexp_substr(str, '[^-@]+', 1, 3) a, regexp_substr(str, '[^-@]+', 1, 4) b
from s;

A          B  
---------- ---
BR12340000 990

答案 2 :(得分:0)

您可以使用regexp_replace来获取最后一个@之后的每个字符,然后用破折号分隔。

with t(str) as
(
select regexp_replace('BR65437812-909@-@BR12340000-990','.*@','') from dual
) 
select regexp_replace(str,'-.*','') as a,
       regexp_replace(str,'.*-','') as b
  from t;

A           B
----------  ---
BR12340000  990

Demo