从值中提取特定的子字符串

时间:2019-07-16 11:17:31

标签: sql regex oracle

特定查询的结果如下:

<?xml version="1.0" encoding="UTF-8"?>
<Attachment content-type="application/temp" name="123_PQ_ABCDEFG_160720190439.tmp"/>

我希望能够从12123 [在这种情况下是name="123_PQ_ABCDEFG_160720190439.tmp"开头的3位数字

注意:所有3位数字都将以“ 12”开头。第三位数可以是任何数字[0-9]。

with test as (
    select '<?xml version="1.0" encoding="UTF-8"?><Attachment content-type="application/ms-excel" name="123_PQ_ABCDEFG_160720190439.tmp"/>' code from dual
)
select code,
CASE
WHEN REGEXP_LIKE(code, '^[12]')
THEN SUBSTR(code,1,3)
END AS code
from test

希望检查以12开头的字符串,然后获取仅3位数的子字符串。

预期结果:123 实际结果:null

2 个答案:

答案 0 :(得分:0)

如果您不需要正则表达式, 试试这个

def app(row):
    return str(row['Error']).replace("\"\""," ")

df['Error'] = df.apply(lambda x: app(x),axis = 1)
print(df['Error'])

答案 1 :(得分:0)

您可以尝试此正则表达式:

with test as (
    select '<?xml version="1.0" encoding="UTF-8"?><Attachment content-type="application/ms-excel" name="123_PQ_ABCDEFG_160720190439.tmp"/>' code from dual
)
select 
 REGEXP_substr(REGEXP_substr(code, '[(name=")](1)(2)(\d)',1,1), '(1)(2)(\d)',1,1)
  AS code_substr,
 code
from test

db<>fiddle demo

干杯!