【问题标题】:Issue with Oracle regexOracle 正则表达式的问题
【发布时间】:2014-08-17 09:20:56
【问题描述】:
select regexp_substr('select count(distinct empno), count(distinct deptno) from emp',
                     'count\(distinct.*\)')
  from dual;

对于上面的查询,我想要输出count(distinct empno),但是上面查询中的“.*”是最后一次出现的“)”而不是第一次出现。

谁能告诉我如何得到我想要的输出?

【问题讨论】:

  • 使用非贪婪表达式 .*? 而不是 .*
  • 我不知道为什么相同的答案。

标签: sql regex oracle oracle11g


【解决方案1】:

The * operator is 'greedy' by default。您允许在distinct) 之间任意数量的任何字符。并包括第一个 ) 本身。

正如 EatÅPeach 建议的那样,您可以使用 ? 使其不贪婪:

贪心运算符匹配尽可能多的匹配项,同时允许其余匹配成功。要使运算符不贪婪,请在其后面加上非贪婪修饰符 (?)

所以在这里,用.*? 代替.*

select regexp_substr(
  'select count(distinct empno), count(distinct deptno) from emp',
    'count\(distinct.*?\)')
from dual;

或者您可以指定它应该是除) 以外的任何字符,使用[^)]* 而不是.*

select regexp_substr(
  'select count(distinct empno), count(distinct deptno) from emp',
    'count\(distinct[^)]*\)')
from dual;

【讨论】:

    【解决方案2】:

    [^)]*代替.*

    select regexp_substr('select count(distinct empno), count(distinct deptno) from emp',
                         'count\(distinct[^)]*\)')
    from dual;
    

    但是,我很惊讶这是必要的。我希望表达式返回第一个结束括号。

    【讨论】:

    • 为什么有必要这样做? .* 默认匹配除换行符以外的任何字符,* 量词意味着它将尝试尽可能多地匹配(贪婪)。
    • @Jerry 。 . .我没有意识到它在 Oracle 中默认为贪婪。这可能与其他正则表达式实现不一致。
    • 好吧,AFAIK,在大多数实现中默认为贪婪。我实际上不记得上次遇到默认为惰性的实现是什么时候了。
    【解决方案3】:

    尝试查找“除')'之外的任何字符”而不是“任何字符”,如下所示:

    select regexp_substr('select count(distinct empno), count(distinct deptno) from emp',
                     'count\(distinct [^\)]*\)') from dual;
    

    【讨论】:

      猜你喜欢
      • 2018-03-29
      • 1970-01-01
      • 2018-07-11
      • 2011-01-25
      • 1970-01-01
      相关资源
      最近更新 更多