【问题标题】:Regex expression oracle sql 11g to parse XML正则表达式 oracle sql 11g 解析 XML
【发布时间】:2015-01-09 22:09:27
【问题描述】:

我在一个表中有一个列,其中包含 xml 类型的数据,但采用 varchar 格式。原始数据示例如下:

  <old_template_code>BEVA30D</old_template_code><old_template_name>Beva
 30D France calls capped
 15p</old_template_name><new_template_code>BEVA24M</new_template_code><new_template_name>Beva 24M France Calls Capped 15p</new_template_name>

我想知道我必须使用什么正则表达式从&lt;old_template_code&gt; 检索例如“BEVA30D”?

我试过了

          REGEXP_SUBSTR(table.column,
            '<old_template_code>*</old_template_code>') "REGEXPR_SUBSTR"

但它不起作用。

【问题讨论】:

    标签: xml regex oracle oracle11g


    【解决方案1】:

    忘记正则表达式。使用原生 XMLType 功能 ...

    select extractValue(xmlparse(content T.column), '/old_template_code')
    from table T;
    

    在基于您的示例 XML 数据的示例中:

    with source$ as (
        select q'{
    <old_template_code>BEVA30D</old_template_code><old_template_name>Beva
     30D France calls capped
     15p</old_template_name><new_template_code>BEVA24M</new_template_code><new_template_name>Beva 24M France Calls Capped 15p</new_template_name>
    }' as source_xml
        from dual
    )
    select extractValue(xmlparse(content source_xml), '/old_template_code')
    from source$;
    

    给了我价值

    BEVA30D
    

    享受吧。

    PS:此外,忘记stackoverflow.com,使用Oracle documentation。 :-)

    【讨论】:

    • 但我需要从表中的列中提取数据。那只是一个示例行。我需要从表中选择 table.column 并获取值
    • 我相信您能够获得示例代码 sn-p 并根据您的需要进行调整。但如果没有,……答案已更新。
    • 不错! +1 为例。一个可能的问题是,应该包含有效 XML 的 varchar 字段几乎肯定会有一些非 xml 垃圾,这可能会导致 XML 解析器问题。
    【解决方案2】:

    XML 方法绝对总是更好的方法。

    仍然是正则表达式方法。

    select regexp_replace(regexp_substr(table.column,'<old_template_code>.*</old_template_code>'),
                          '(<old_template_code>)(.*)(</old_template_code>)',
                           '\2')
    from table;
    

    【讨论】:

    • 我接受这个答案只是因为 xml 解析器在 150 行之后失败,可能是因为某些 xml 数据不正确。然而,这种方法并没有失败。
    • 我开始对用简单的正则表达式破解它感兴趣。我也知道缺点。
    • @user3793865,在您的问题中,您没有在您的 XML 列中提及任何可能的垃圾数据,也没有给我们提供此类垃圾数据的示例。
    猜你喜欢
    • 1970-01-01
    • 2012-01-25
    • 1970-01-01
    • 2015-04-29
    • 1970-01-01
    • 2011-10-28
    • 2021-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多