问题
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