[英]Postgres function to split word to arrays with extra logic
我一直在玩 psql 并将名称拆分为数组,例如:
select string_to_array('joseph jones', ' ');
string_to_array
-----------------
{joseph,jones}
这完全符合我的预期。
但是,我的数据集包含许多前面带有“o”的姓氏。
select string_to_array('joseph o carroll', ' ');
string_to_array
-----------------
{joseph,o,carroll}
有什么办法可以添加一些额外的逻辑,以便如果一个词前面有一个“ o ”,那么它会被捆绑到下一个词中?
所以joseph o carroll
会返回{joseph,o carroll}
通过使用正则表达式,我想我找到了一个解决方案:
select regexp_split_to_array('joseph o jones','(?<!o)(\\s+)');
你不能仅仅使用(?<!o)\\s+
,试试它对romeo bones
。 由于名字以o
结尾,表达式不匹配。
用
select regexp_split_to_array('joseph o jones','(?<!\yo)\s+');
解释
--------------------------------------------------------------------------------
(?<! look behind to see if there is not:
--------------------------------------------------------------------------------
\y the boundary between a word char (\w)
and something that is not a word char
--------------------------------------------------------------------------------
o 'o'
--------------------------------------------------------------------------------
) end of look-behind
--------------------------------------------------------------------------------
\s+ whitespace (\n, \r, \t, \f, and " ") (1 or
more times (matching the most amount
possible))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.