正则表达式仅用双引号替换第一个分号

Regular expression to replace only the first semi colon with a double quote

有一个以分号分隔的数据转储。

如何将该数据加载到 Postgres SQL 数据库?

City;Latitude;Longitude
London;51.50;0.12
Paris;48.85;2.35

我想使用 Atom 文本编辑器从这些数据中准备一个插入语句。 但是还有另一个挑战,第一个分号需要用单引号和逗号代替才能形成有效的插入语句。

table 的 DDL:

create table cities (
    name varchar(100),
    Latitude float,
    Longitude float
);

插入语句应如下所示:

insert into cities values('London',51.50,0.12);
insert into cities values('Paris',48.85,2.35);

但我只能使用 atom 文本编辑器生成这个:

insert into cities values('London,51.50,0.12);
insert into cities values('Paris,48.85,2.35);

以上是用逗号代替分号实现的。使用 ^ 在开头添加 insert into cities values(' 并使用 $ 在添加中添加 );

所以问题是,原子文本编辑器应该使用什么正则表达式来替换第一次出现的分号?

这应该有效:

找到:^(.+);(.+);(.+) 替换:insert into cities values('',,);

(我推荐这个免费资源作为试验正则表达式的好方法:https://regex101.com/

您无需预先编辑输入字符串,也无需将每个条目单独插入;它可以在一个 Insert 语句中完成。您有一个包含已知组件数和分隔符的字符串,因此请使用函数 regexp_split_to_array 以分号 (;) 分隔。然后直接插入 table 引用元素并根据需要进行转换。参见 Demo

with loc( loc_str) as ( values('London;51.50;0.12'), ('Paris;48.85;2.35')) 
insert into cities(name, latitude, longitude) 
     select loc_part[1], loc_part[2]::float,loc_part[3]::float
       from ( select regexp_split_to_array(loc_str,';') loc_part from loc) l;

您还可以使用 COPY 从源文件加载暂存 table,然后使用与上述基本相同的方法从中填充您的 table。 (也在演示中)