显示指定字符之间的一部分文本 oracle sql plus

display a portion of text that is inbetween specified characters oracle sql plus

原始数据是这样的:

xy12j-ty75#pid
bvbn-8ffde#pid
gonw-5gt#pid
qertt-yytre#pid

我只需要像这样显示“-”和“#”之间的数据:

ty75
8ffde
5gt
yytre

我写了 2 个不同的代码,如果将它们放在一起(以某种方式)我认为会起作用。

我的代码 1(显示“#”左侧的所有内容:

SQL> select substr(pcode, 1, (instr (pcode, '#'))-1)
  2  from products ;

显示这个:

----------------------------------------
xy12j-ty75
bvbn-8ffde
vb-5gt
skr-yytre

我的代码 2 显示了“-”右侧的所有内容:

SQL> select ltrim(pcode, (substr(pcode, 1, (instr(pcode, '-')))))
  2  from products ;

显示这个:

----------------------------------------
ttg#pid
lbcx#pid
gonw#pid
ertt#pid

我为此使用 subsr 和 instr 函数也很重要。

假设您的字符串始终与样本数据的模式相匹配,您可以这样组合 instrsubstr

select substr(pCode,
              instr(pCode, '-') + 1,
              instr(pCode, '#') - instr(pCode, '-') -1 
             )
    from products

比如这个

with products(pCode) as (
    select 'xy12j-ty75#pid' from dual union all
    select 'bvbn-8ffde#pid' from dual union all
    select 'gonw-5gt#pid' from dual union all
    select 'qertt-yytre#pid' from dual
)
select substr(pCode, instr(pCode, '-')+1, instr(pCode, '#') - instr(pCode, '-')-1)
from products

给出:

ty75
8ffde
5gt
yytre

此处使用 instr'-' 之后的字符开始,并结合使用 instrsubstr 来计算 [ 之间的字符数=16=] 和 '#'.

您可以使用 replace 应用于 instr&substr 字符串操作:

select replace( substr(pcode, 1, (instr (pcode, '#'))-1), 
                substr(pcode, 1, (instr (pcode, '-'))) ) "Result Set"
  from products;

Result Set
----------
ty75
8ffde
5gt
yytre

Demo

您可以使用正则表达式

select regexp_substr(pcode, '(.*?-)(.*?)#',1,1,'',2) from products 

例如

with products (pcode) as (
    select 'xy12j-ty75#pid' from dual union all
    select 'bvbn-8ffde#pid' from dual union all
    select 'gonw-5gt#pid' from dual union all
    select 'qertt-yytre#pid' from dual
)
select regexp_substr(pcode, '(.*?-)(.*?)#',1,1,'',2) from products