[英]PostgreSQL “invalid regular expression: invalid escape \ sequence” when using Regex constraint
This is my SQL code:这是我的 SQL 代码:
CREATE TABLE country (
id serial NOT NULL PRIMARY KEY,
name varchar(100) NOT NULL CHECK(name ~ '^[-\p{L} ]{2,100}$'),
code varchar(3) NOT NULL
);
Notice the regex constraint at the name
attribute.注意
name
属性的正则表达式约束。 The code above will result in ERROR: invalid regular expression: invalid escape \ sequence
.上面的代码将导致
ERROR: invalid regular expression: invalid escape \ sequence
。
I tried using escape CHECK(name ~ E'^[-\\p{L} ]{2,100}$')
but again resulted in ERROR: invalid regular expression: invalid escape \ sequence
.我尝试使用 escape
CHECK(name ~ E'^[-\\p{L} ]{2,100}$')
但再次导致ERROR: invalid regular expression: invalid escape \ sequence
。
I am also aware that if I do CHECK(name ~ '^[-\\p{L} ]{2,100}$'),
or CHECK(name ~ E'^[-\p{L} ]{2,100}$'),
- the SQL will receive wrong Regex and therefore will throw a constraint violation when inserting valid data.我也知道,如果我执行
CHECK(name ~ '^[-\\p{L} ]{2,100}$'),
或CHECK(name ~ E'^[-\p{L} ]{2,100}$'),
- SQL 将收到错误的正则表达式,因此在插入有效数据时会引发约束冲突。
Does PostgreSQL regex constraints not support regex patterns ( \p
) or something like that? PostgreSQL 正则表达式约束是否不支持正则表达式模式(
\p
)或类似的东西?
Edit #1编辑#1
The Regex ^[-\p{L} ]{2,100}$
is basically allows country name that are between 2-100 characters and the allowed characters are hyphen, white-space and all letters (including latin letters).正则表达式
^[-\p{L} ]{2,100}$
基本上允许 2-100 个字符之间的国家名称,允许的字符是连字符、空格和所有字母(包括拉丁字母)。
NOTE: The SQL runs perfectly fine during the table creation but will throw the error when inserting valid data.注意: SQL 在创建表期间运行良好,但在插入有效数据时会抛出错误。
Additional Note: I am using PostgreSQL 12.1附加说明:我使用的是 PostgreSQL 12.1
The \p{L}
Unicode category (property) class matches any letter, but it is not supported in PostgreSQL regex . \p{L}
Unicode 类别(属性) class 匹配任何字母,但在PostgreSQL 正则表达式中不支持。
You may get the same behavior using a [:alpha:]
POSIX character class您可以使用
[:alpha:]
POSIX 字符 class 获得相同的行为
'^[-[:alpha:] ]{2,100}$'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.