一个正则表达式来匹配不同位置的部件
我正在尝试使用正则表达式解析 DSN(来自 Symfony 应用程序),以便与辅助应用程序链接,但使用相同的数据库。
我当前拥有的 DSN 是:
mysql:dbname=my_db_name;host=localhost
正则表达式为:(
/^(\w+):(dbname=(\w+))?;?(host=(\w+))?/
使用 preg_match()
)。这匹配正常,但在我的测试环境中失败,因为 DSN 元素被切换,因此:
mysql:host=localhost;dbname=my_testdb_name
我可以将它们切换,是的:-)但我确信可以使用以下命令从两个 DSN 中提取主机和数据库名部分一个正则表达式,我希望能够同时增强我的知识;-) 有什么办法可以做到这一点吗?
I'm trying to parse a DSN (from a Symfony application) using regular expressions, in order to link with a secondary application, but using the same database.
The DSN I currently have is:
mysql:dbname=my_db_name;host=localhost
with a regex of:
/^(\w+):(dbname=(\w+))?;?(host=(\w+))?/
(using preg_match()
). This matches OK, but fails in my test environment because the DSN elements are switched around, thus:
mysql:host=localhost;dbname=my_testdb_name
I could just switch them round, yes :-) but I'm sure that extraction of the host and dbname parts from both DSNs is possible with a single regular expression, and I'd like to be able to enhance my knowledge at the same time ;-) Is there a way I can do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我将字符串拆分为“;”然后在分割字符串的每个部分上对我感兴趣的每个部分使用单独的正则表达式。
尝试这样做,以便正则表达式匹配任何一方可能有点矫枉过正,并且如果您添加第三个或第四个要检查的东西,很快就会失去控制。
事实上,你也许可以在不实际分割字符串的情况下逃脱。
编辑:
啊,重新阅读问题,似乎该字符串是较长字符串的一部分。
所以你可以这样做,
这可以简化为:
你可能需要调整你的正则表达式风格,我只习惯.net
I'd split the string on ';' then use individual regexs for each part i was interested in, on each part of the split string.
trying to do it so the regex matches which ever way round is probably a bit of overkill, and would quickly get out of control if you added a third or fourth thing to check for.
in fact you might be able to get away without actuall splitting the string.
EDIT:
Ahh just re-read the question, seems this string is part of a longer string.
so you could do this
which could be reduced to:
you might need to adjust for your flavour of regex, I'm only used to .net
以下表达式可以匹配两个 DSN
但它也可以匹配 mysql:host=localhost;host=localhost ......
The following expression could match the two DSN
But it could match mysql:host=localhost;host=localhost too...