regex for postgres array

huangapple go评论75阅读模式
英文:

regex for postgres array

问题

我正在使用不支持Postgres数组的ORM,所以我正在尝试一些技巧来添加"支持"。

目前,我需要将Postgres数组字符串转换为编程语言的数组。

Postgres数组字符串表示的示例:

{"bla, bla",bla,"bu bu",bu}

如果有空格,Postgres会自动添加引号,如果没有空格,则元素没有引号。

你会使用什么正则表达式来提取这个数组?所以结果应该是:

array := []{"bla, bla", "bla", "bu bu", "bu"}

我正在使用Go

数组是一维的,所以类似于:

CREATE TABLE test (
    something  text[]
);
英文:

I am using ORM which doesn't support postgres array, so I am trying to do some hacks to add "support".

Currently I have to convert postgres array string into array of programming language.

Example of postgres array string representation:

{"bla, bla",bla,"bu bu",bu}

So if there are spaces, postgres is automatically adding quotes, if not, then element is without quotes.

What regex you would use to get array out of this? So result should be:

array := []{"bla, bla", "bla", "bu bu", "bu"}

I am using Go.

Arrays are one dimensional, so something like:

CREATE TABLE test (
    something  text[]
);

答案1

得分: 1

我不熟悉golang,但可以使用以下搜索正则表达式:

(?<=,)(?=[^"](([^"]*"){2})*[^"]*$)|(?<=[^"])(?=,(([^"]*"){2})*[^"]*$)

并将匹配项替换为引号 "

请参考正则表达式实时演示

然后在前面添加 []

假设转义的引号不会出现在值中。

英文:

I'm not au fait with golang, but use this search regex

(?&lt;=,)(?=[^&quot;](([^&quot;]*&quot;){2})*[^&quot;]*$)|(?&lt;=[^&quot;])(?=,(([^&quot;]*&quot;){2})*[^&quot;]*$)

and replace matches with a quote &quot;.

See regex live demo.

Then add &quot;[]&quot; at the front.

Assumes (escaped) quotes never appear within values.

huangapple
  • 本文由 发表于 2015年6月3日 16:12:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/30614402.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定