我正在编写一个正则表达式来捕获PostgreSQL的连接字符串.连接字符串的格式如下:

(postgresql|postgres)://[userspec@][hostspec][/dbname][?paramspec]

where userspec is: user[:password]
and hostspec is: [host][:port][,...]
and paramspec is: name=value[&...]

这里,userspecportdbnameparamspec是可选的.

连接字符串的示例如下:

postgresql://localhost
postgresql://localhost:5433
postgresql://localhost/mydb
postgresql://user@localhost
postgresql://user:secret@localhost
postgresql://other@localhost/otherdb?connect_timeout=10&application_name=myapp
postgresql://host1:123,host2:456/somedb?application_name=myapp
postgres://myuser:mypassword@192.168.0.100:5432/mydatabase
postgresql://192.168.0.100/mydb

我try 用下面的正则表达式来捕获连接字符串,并在捕获组中捕获主机规范.

(postgresql|postgres):\/\/((?:[^:@]*)(?::[^@]*)?@{0,1})?(?<server>[^\/\?]+)\b

但是,当用户规范不存在时,正则表达式无法正确捕获.可以找到here个正则表达式.

您能指出如何避免对用户规范的贪婪判断,并在每一行中找到主机规范吗?

推荐答案

以下是对您的正则表达式所做的一些更正,以使其按您预期的方式工作.

  • (?:[^:@]*)可以简化为[^:@]*.如果你没有把它作为一个组来处理,你不需要把它放在括号里,然后用?:把它变成非组.我还在它里面添加了\s个,这样它就不会爬行来吃任何换行符
  • 由于上述原因,(?::[^@]*)?更改为(?::[^@\s]*)?,包括\s
  • @{0,1}根据需要改为@.另外,你也可以把@{0,1}写成@?
  • 在服务器组的最后一组中,[^\/\?]+更改为[^\/\?\s]+以再次包括\s

通过上面的更改,它似乎正在按照您的预期工作.

Updated Regex Demo

如果这对你有效,请让我知道.

Postgresql相关问答推荐

为什么Postgres优化器切换到嵌套循环进行连接?

列不明确

在特定值的组聚合中添加标签列作为结果

IF 块中的 CREATE FUNCTION 语句抛出错误,同时运行它自己的作品

如何在 postgres 中查询键设置为空值的 jsonb 字段

gorm 创建并返回值 many2many

如何计算过滤器中的百分比

Postgres 根据自己的估计 Select 一个更费时的查询计划

转换数组类型

当脚本工作时,Postgres now() 时间戳不会改变

如何将 postgres 数据库转换为 sqlite

在 PostgreSQL 中Explain与explain analyze

如何在可选参数上查询 postgres?

无法登录 PostgreSQL 数据库

Select 中的 PostgreSQL 正则表达式捕获组

将数据从 MS SQL 迁移到 PostgreSQL?

postgresql 查询以显示用户的组

如何缩小 pg_toast 表?

什么是 Postgres session?

Postgresql 对象 ID 和元组