Issue with Oracle regex

放肆的年华 提交于 2019-12-11 15:07:03

问题


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

For the above query I want output count(distinct empno), but the ".*" in the above query is taking the last occurrence of ")" and not the first occurrence.

Can anyone please tell how to get the output I want?


回答1:


The * operator is 'greedy' by default. You're allowing any characters between distinct and ), in any quantity. and including the first ) itself.

As EatÅPeach suggested, you can make it non-greedy with ?:

A greedy operator matches as many occurrences as possible while allowing the rest of the match to succeed. To make the operator nongreedy, follow it with the nongreedy modifier (?)

So here, with .*? instead of .*:

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

Or you can specify it should be any character except ) with [^)]* instead of .*.

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



回答2:


Instead of .*, use [^)]*:

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

However, I'm surprised that this is necessary. I would expect the expression to return the first closing paren.




回答3:


Try looking for "any char except ')'" instead of "any char", as in the following:

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


来源:https://stackoverflow.com/questions/24431931/issue-with-oracle-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!