Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex根据字符串内容匹配不同的组_Regex_Postgresql - Fatal编程技术网

Regex根据字符串内容匹配不同的组

Regex根据字符串内容匹配不同的组,regex,postgresql,Regex,Postgresql,要求 我有一个Postgres列,包含两种形式的值:个人名称和公司名称。个人名称包含逗号,而公司名称不包含逗号 _owner_titlecase ------------------------- McCartney, James Paul Lennon, John Winston Ono Harrison, George Starkey, Richard The Beatles 我必须生成一个仅缩写个人姓名的查询,如下所示: regexp_replace ------------------

要求

我有一个Postgres列,包含两种形式的值:个人名称和公司名称。个人名称包含逗号,而公司名称不包含逗号

_owner_titlecase
-------------------------
McCartney, James Paul
Lennon, John Winston Ono
Harrison, George
Starkey, Richard
The Beatles
我必须生成一个仅缩写个人姓名的查询,如下所示:

regexp_replace
-------------------------
McCartney, J P
Lennon, J W O
Harrison, G
Starkey, R
The Beatles
背景

经过一些性能测试后,我意识到我不能使用
CASE
来区别对待这两种行类型(如
案例中的“所有者”\u titlecase~,“regexp\u replace…”
)。所以我希望有一种方法可以编写一个单独的正则表达式,以区别对待这两种类型

我正在学习如何处理人名的首字母部分,现在正在使用
(^\w+)\Y\w
regex,如下所示:

, regexp_replace(_owner_titlecase
    , '(^|;\s+)(\w+)|\Y\w'
    , '\1', 'g')
现在我把范围扩大到公司名称,当然披头士乐队的缩写是B

\Y
是一个Postgres regex字符类,我了解到它只在不是单词开头或结尾的点匹配。虽然特殊的Postgres类看起来在这种情况下很有用,但坚持使用通用的正则表达式功能实际上是很有用的,因此我可以在regex101.com之类的地方测试它们。目前我唯一的Postgres测试平台有些笨拙,无法提供调试帮助


整个故事是,我们有一个CartoDB地图,我们想在上面叠加一个包含财产所有者姓名的图层。有些属性靠得很近,所有者名称列表可能很长,因此需要缩写。

我建议您使用

regexp_replace(_owner_titlecase,
     '^([^,]*)$|(^|;\s+)([\w\u0027]+)|\Y\w',
     '\1\2\3', 'g')
关键是,您只需要删除前面带有单词char的任何单词char,并保留所有其他内容。因此,任何异常(需要保留的文本)都可以作为捕获的替代分支添加到需要删除的模式之前


^([^,]*)$
部分仅匹配和捕获由0+字符组成的字符串,而不是
,并使用
\1
将其恢复到替换结果中。

我相信您可以使用
^([^,]*)$|(^ s+)(\w+)\Y\w
模式并替换为
“\1\2\3”
再次感谢@Wictor。这适用于大多数人名。我可能不太理解这个问题,但你不能在像
where name像“%”,%%这样的
where
@Fallenhero之前用
where
-语句进行过滤,因为这会阻止公司名称出现在结果中,所以不起作用,因此在地图上,
O'Brien,Andrew John
问题(返回为
O'B,A J
)可以通过稍微扩展模式到
^([^,]*)$|(^ |;\s+([\w\u0027]+)\Y[\w\u0027]
来轻松解决。不过,我不确定
|
的哪一方负责。我认为最后一个分支中的
\u0027
是不必要的。看见看起来这已经足够了。名称不能有
O'
前缀。