场景:匹配除字符串“J01FA09”以外的任何以“J01”开头的字符串。
我很困惑为什么下面的代码什么都不返回:
SELECT 1
WHERE
'^J01(?!FA09).*' ~ 'J01FA10'
当我可以在 regexr.com 上看到时它正在运行(我意识到有不同风格的正则表达式,这可能是网站运行的原因)。
我已在 postgres documentation 中确认不过,支持负面展望。
表 9-15。正则表达式约束
(?!re) negative lookahead matches at any point where no substring matching re begins (AREs only). Lookahead constraints cannot contain back references (see Section 9.7.3.3), and all parentheses within them are considered non-capturing.
最佳答案
Match any string that starts with "J01" except the string "J01FA09".
你可以在没有正则表达式的情况下使用
WHERE s LIKE 'J01%' AND s != 'J01FA09'
这里,LIKE 'J01%'
要求字符串以 J01
开头,后面可能有任何字符,并且 s != 'J01FA09'
将过滤掉匹配项。
如果你想用正则表达式实现同样的效果,使用
WHERE s ~ '^J01(?!FA09$)'
^
匹配字符串的开头,J01
匹配文字 J01
子字符串和 (?!FA09$)
断言在 J01
之后没有 FA09
后跟字符串位置的结尾。如果 FA09
出现并且后面有字符串结尾,则不会返回任何匹配项。
参见 online demo :
CREATE TABLE table1
(s character varying)
;
INSERT INTO table1
(s)
VALUES
('J01NNN'),
('J01FFF'),
('J01FA09'),
('J02FA09')
;
SELECT * FROM table1 WHERE s ~ '^J01(?!FA09$)';
SELECT * FROM table1 WHERE s LIKE 'J01%' AND s != 'J01FA09';
关于regex - Postgres 正则表达式负前瞻,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43875508/