我正在编写一个正则表达式来捕获PostgreSQL的连接字符串.连接字符串的格式如下:
(postgresql|postgres)://[userspec@][hostspec][/dbname][?paramspec]
where userspec is: user[:password]
and hostspec is: [host][:port][,...]
and paramspec is: name=value[&...]
这里,userspec、port、dbname和paramspec是可选的.
连接字符串的示例如下:
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个正则表达式.
您能指出如何避免对用户规范的贪婪判断,并在每一行中找到主机规范吗?