计算字符串中的字符及其位置

时间:2017-06-16 07:52:43

标签: sql oracle plsql

我有一个字符串' ### ABC ## DE'。我需要找出'#'的位置。然后有多少'#'之后。例如,在这种情况下,输出应为

position count
=======  ======
1           3
7           2

是否可以在sql语句中执行此操作,或者我们是否需要plsql块?

1 个答案:

答案 0 :(得分:4)

这是在SQL语句中执行此操作的方法:

WITH sample_data AS (SELECT '###ABC##DE' str FROM dual UNION ALL
                     SELECT 'A#B#C#D#E##' str FROM dual UNION ALL
                     SELECT 'ABCDE' str FROM dual)
SELECT str,
       NVL(length(regexp_substr(str, '#+', 1, LEVEL)), 0) num_hashes,
       regexp_instr(str, '#+', 1, LEVEL) hash_pos
FROM   sample_data
CONNECT BY regexp_substr(str, '#+', 1, LEVEL) IS NOT NULL
AND PRIOR str = str
AND PRIOR sys_guid() IS NOT NULL;

STR         NUM_HASHES   HASH_POS
----------- ---------- ----------
###ABC##DE           3          1
###ABC##DE           2          7
A#B#C#D#E##          1          2
A#B#C#D#E##          1          4
A#B#C#D#E##          1          6
A#B#C#D#E##          1          8
A#B#C#D#E##          2         10
ABCDE                0          0

这样做是使用分层查询(即connect by部分)来遍历字符串并搜索1个或多个#字符。它将为每个组输出一行。