如何计算 Oracle varchar 值中某个字符出现的次数?
如何计算 varchar2 字符串中字符 -
出现的次数?
例子:
select XXX('123-345-566', '-') from dual;
----------------------------------------
2
How can I count number of occurrences of the character -
in a varchar2 string?
Example:
select XXX('123-345-566', '-') from dual;
----------------------------------------
2
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
从技术上讲
,如果要检查的字符串只包含要计数的字符,则上述查询将返回 NULL;以下查询将在所有情况下给出正确答案:
coalesce
中的最后一个 0 捕获您在空字符串中计数的情况(即 NULL,因为 ORACLE 中的 length(NULL) = NULL) 。Here you go:
Technically, if the string you want to check contains only the character you want to count, the above query will return NULL; the following query will give the correct answer in all cases:
The final 0 in
coalesce
catches the case where you're counting in an empty string (i.e. NULL, because length(NULL) = NULL in ORACLE).REGEXP_COUNT 应该做这件事:
REGEXP_COUNT should do the trick:
这是一个想法:尝试用空字符串替换所有不是破折号字符的内容。然后数一下还剩下多少个破折号。
Here's an idea: try replacing everything that is not a dash char with empty string. Then count how many dashes remained.
我刚刚遇到了非常类似的问题...但 RegExp_Count 无法解决它。
字符串 '16,124,3,3,1,0,' 包含 ',3,' 有多少次?正如我们看到的 2 次,但 RegExp_Count 仅返回 1。同样的情况是“bbaaaacc”,当查看“aa”时,应该是 3 次,而 RegExp_Count 仅返回 2。
我花了一些时间在网络上研究解决方案。找不到......所以我编写了自己的函数,返回真实的出现次数。希望它会有用。
I justed faced very similar problem... BUT RegExp_Count couldn't resolved it.
How many times string '16,124,3,3,1,0,' contains ',3,'? As we see 2 times, but RegExp_Count returns just 1. Same thing is with ''bbaaaacc' and when looking in it 'aa' - should be 3 times and RegExp_Count returns just 2.
I lost some time to research solution on web. Couldn't' find... so i wrote my own function that returns TRUE number of occurance. Hope it will be usefull.
我想到了
I thought of
你可以试试这个
,它“正确地”计算“bbaaaacc”中有多少个“aa”
You can try this
it counts "properly" olso for how many 'aa' in 'bbaaaacc'
这是一个适用于字符和子字符串的解决方案:
其中 a 是您在其中搜索 b 出现的字符串,
祝您有美好的一天!
here is a solution that will function for both characters and substrings:
where a is the string in which you search the occurrence of b
have a nice day!