Postgres asterisc 正则表达式量词不起作用
Postgres asterisc regex quantifier not working
在 Postgres 9.5.1 中,以下命令有效:
select regexp_replace('JamesBond007','\d+','');
输出:
JamesBond
但是星号似乎不起作用:
select regexp_replace('JamesBond007','\d*','');
它产生:
JamesBond007
当我把一些东西作为替换字符串时,会发生更奇怪的事情:
select regexp_replace('JamesBond007','\d+','008');
结果:
JamesBond008
而
select regexp_replace('JamesBond007','\d*','008');
还给我:
008JamesBond007
Postgres 文档说 * = 0 个或多个原子匹配的序列。
那么这里发生了什么? (N.B。在 Oracle 中,以上所有操作都按预期工作)
问题是 \d*
可以匹配一个空字符串,而你没有传递标志 g
。
The flags parameter is an optional text string containing zero or more single-letter flags that change the function's behavior. Flag i
specifies case-insensitive matching, while flag g
specifies replacement of each matching substring rather than only the first one.
\d*
匹配 JamesBond007
字符串开头的空位置,并且由于 g
未传递,因此空字符串被替换为 008
时您使用 select regexp_replace('JamesBond007','\d*','008');
并且结果是预期的 - 008JamesBond007
.
与select regexp_replace('JamesBond007','\d*','');
一样,\d*
再次匹配字符串开头的空位置,并将其替换为空字符串(无可见变化)。
请注意,Oracle 的 REGEXP_REPLACE
默认替换所有匹配项:
By default, the function returns source_char
with every occurrence of the regular expression pattern replaced with replace_string
.
一般来说,在基于正则表达式的替换中使用匹配空字符串的模式时应该谨慎 functions/methods。仅当您了解自己在做什么时才这样做。如果您想替换数字,您通常 想要找到至少 1 个数字。否则,为什么首先要删除字符串中不存在的内容?
在 Postgres 9.5.1 中,以下命令有效:
select regexp_replace('JamesBond007','\d+','');
输出:
JamesBond
但是星号似乎不起作用:
select regexp_replace('JamesBond007','\d*','');
它产生:
JamesBond007
当我把一些东西作为替换字符串时,会发生更奇怪的事情:
select regexp_replace('JamesBond007','\d+','008');
结果:
JamesBond008
而
select regexp_replace('JamesBond007','\d*','008');
还给我:
008JamesBond007
Postgres 文档说 * = 0 个或多个原子匹配的序列。 那么这里发生了什么? (N.B。在 Oracle 中,以上所有操作都按预期工作)
问题是 \d*
可以匹配一个空字符串,而你没有传递标志 g
。
The flags parameter is an optional text string containing zero or more single-letter flags that change the function's behavior. Flag
i
specifies case-insensitive matching, while flagg
specifies replacement of each matching substring rather than only the first one.
\d*
匹配 JamesBond007
字符串开头的空位置,并且由于 g
未传递,因此空字符串被替换为 008
时您使用 select regexp_replace('JamesBond007','\d*','008');
并且结果是预期的 - 008JamesBond007
.
与select regexp_replace('JamesBond007','\d*','');
一样,\d*
再次匹配字符串开头的空位置,并将其替换为空字符串(无可见变化)。
请注意,Oracle 的 REGEXP_REPLACE
默认替换所有匹配项:
By default, the function returns
source_char
with every occurrence of the regular expression pattern replaced withreplace_string
.
一般来说,在基于正则表达式的替换中使用匹配空字符串的模式时应该谨慎 functions/methods。仅当您了解自己在做什么时才这样做。如果您想替换数字,您通常 想要找到至少 1 个数字。否则,为什么首先要删除字符串中不存在的内容?