我想编写一个regexp_like函数来识别字符串是否包含两个重复字符。它只会识别一个字符串,该字符串具有交替的数字,并且只包含两个唯一的数字,但唯一的数字不能重复,它必须交替。
要求:
正则表达式应与787878787
的模式匹配,但 NOT 匹配模式787878788
它不应该考虑像000000000
答案 0 :(得分:1)
您可能会这样做 -
SQL> WITH DATA AS(
2 SELECT '787878787' str FROM dual UNION ALL
3 SELECT '787878788' FROM dual
4 )
5 SELECT *
6 FROM DATA
7 WHERE REGEXP_LIKE(str, '(\d+?)\1')
8 AND SUBSTR(str, 1,1) = SUBSTR(str, -1, 1)
9 /
STR
---------
787878787
SQL>
由于您只处理数字,我使用\d
。
\d+?
将匹配数字,\1
是捕获的数字。 substr
条件中的AND
正在检查字符串的第一个和最后一个数字是否相同。
编辑:OP的附加要求
要避免使用00000000
这样的数字,您需要在谓词中添加NOT
条件。
SQL> WITH DATA AS
2 ( SELECT '787878787' str FROM dual
3 UNION ALL
4 SELECT '787878788' FROM dual
5 UNION ALL
6 SELECT '787878788' FROM dual
7 )
8 SELECT *
9 FROM DATA
10 WHERE REGEXP_LIKE(str, '(\d+?)\1')
11 AND SUBSTR(str, 1,1) = SUBSTR(str, -1, 1)
12 AND SUBSTR(str, 2,1) <> SUBSTR(str, -1, 1)
13 /
STR
---------
787878787
SQL>
答案 1 :(得分:1)
我想你想要以下内容:
WITH t1 AS (
SELECT '787878787' AS str FROM dual
UNION
SELECT '787878788' AS str FROM dual
UNION
SELECT '7878787878' AS str FROM dual
UNION
SELECT '78' AS str FROM dual
)
SELECT * FROM t1
WHERE REGEXP_LIKE(str, '^(.)(.)(\1\2)*\1?$')
AND SUBSTR(str, 1, 1) != SUBSTR(str, 2, 1)
这将涵盖字符串以与其开头相同的字符结尾的情况(在要求中提到)。如果您只想要数字,请将正则表达式中的.
替换为\d
。
<强>更新强>
以下是正则表达式的分解:
^ = start of string
(.) = first character - can be anything - in parentheses to capture it and use it in a backreference
(.) = second character - can be anything
\1 = backreference to first captured group
\2 = backreference to second captured group
(\1\2)* = These should appear together zero or more times
\1? = The first captured group should appear zero or one times
$ = end of the string
希望这有帮助。
答案 2 :(得分:0)
你可以尝试:
^(..)\1*$
故障:
^ - assert beginning of line
(..) - capture the first 2 characters
\1* - repeat the captured group pattern zero or more times
$ - assert end of line
在oracle中未经测试......