【问题标题】:Extracting double quoted string from the given pattern从给定模式中提取双引号字符串
【发布时间】:2012-02-17 14:15:35
【问题描述】:

请任何人帮助我,

我有一个类似的字符串

varchar2 b:

'i hav to extract second double queted string "string one".and the "Second one"'

预期结果:第二个

varchar2 一个:

' here is "table". "tiger" some other txt ';

预期结果是老虎

从上面的字符串模式中,我必须提取第二个双引号字符串。请在这方面帮助我我已经尝试了很多尝试

【问题讨论】:

    标签: oracle plsql


    【解决方案1】:

    在 11g 中,您可以将 regexp_substr 与新参数一起使用(允许仅匹配子表达式):

    SQL> with data as (
      2    select 'i hav to [...] "string one".and the "Second one"' txt from dual
      3    union all
      4    select ' here is "table". "tiger" some other txt ' from dual)
      5  SELECT regexp_substr(txt,'"([^"]*)"', 1, 2, '', 1) FROM data;
    
    REGEXP_SUBSTR(TXT,'"([^"]*)"',1,2,'',1)
    ------------------------------------------------------------------------------
    Second one
    tiger
    

    在 10g 中,您可以使用 replace 删除多余的 "

    SQL> with data as (
      2    select 'i hav to [...] "string one".and the "Second one"' txt from dual
      3    union all
      4    select ' here is "table". "tiger" some other txt ' from dual)
      5  SELECT replace(regexp_substr(txt,'"[^"]*"', 1, 2),
      6                 '"', '')
      7    FROM data;
    
    REPLACE(REGEXP_SUBSTR(TXT,'"[^"]*"',1,2),'"','')
    ------------------------------------------------
    Second one
    tiger
    

    【讨论】:

    • +1 不错,没玩过正则表达式。我可能会这样做:-)
    【解决方案2】:

    你可以使用REGEXP_REPLACE:

    WITH t AS (
       SELECT 'i hav to extract second double queted string "string one".and the "Second one"'  as x FROM dual
       UNION
       SELECT ' here is "table". "tiger" some other txt ' as x FROM dual)
    SELECT x,
           REGEXP_REPLACE(x, '^.*".*".*(".*").*$', '\1')
      FROM t;
    

    返回:

    "tiger"
    "Second one"
    

    希望对你有帮助...

    如果您不想要引号,请使用:

    REGEXP_REPLACE(x, '^.*".*".*"(.*)".*$', '\1')
    

    【讨论】:

    • +1,虽然 regexp_replace 的问题是如果没有匹配,它会返回整个字符串(而不是 NULL)。
    【解决方案3】:

    使用instr() 获取字符索引(以及要获取哪些出现)和substr() 获取字符串子字符串的示例:

    select 
        substr(str,
            instr(str, '"', 1,3)+1, 
            instr(str, '"', 1, 4)- instr(str, '"', 1,3)-1)
    from
       (select 'here is "table". "tiger" some other txt' str from dual) strt;
    

    这里substr 使用instr(str, '"',1,3) 得到'"'的第三个出现。然后它使用instr(str, '"', 1, 4) 得到第四个出现但我们必须减去第三个'"' 的位置,因为这个参数是子字符串的文本大小(即在我们的例子中,引号之间的文本)。

    您可以改进我们如何获得第四次出现,因为它再次从位置 1 开始搜索,而不是位置 3。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-19
      • 2018-01-25
      • 2021-05-21
      • 1970-01-01
      • 2013-11-09
      • 2023-03-06
      相关资源
      最近更新 更多