One regex to match parts at different positions

I am trying to parse a DSN (from a Symfony application) using regular expressions to link it to a secondary application, but using the same database.

DSN currently has:

mysql:dbname=my_db_name;host=localhost

      

with regex:

/^(\w+):(dbname=(\w+))?;?(host=(\w+))?/

      

(using preg_match()

). This matches OK, but doesn't work in my test environment because DSN items are toggled, thus:

mysql:host=localhost;dbname=my_testdb_name

      

I could just switch them, yes :-), but I'm pretty sure that extracting the host and dbname parts from both DSNs is possible with a single regex, and I would like to be able to improve my knowledge at the same time ;-) Is there is the way i can do this?

+2


a source to share


2 answers


I would split the string by ';' then use separate regex for each part of interest to me, on each part of the split line.

trying to do this to get a regex to match what it ever was might be a bit over the top, and quickly get out of hand if you add a third or fourth thing to check.

in fact you could get away without the actual separating the string.

EDIT:

Ahh just rereads the question, it seems this line is part of a longer line.



so you can do it

/^(\w+):((dbname|host)=(\w+))?;?((dbname|host)=(\w+))?/

      

which can be boiled down to:

    /^(\w+):((dbname|host)=(\w+));?+

      

you may need to customize your regex flavor, I only use .net

+1


a source


The following expression can match two DSNs

/^(\w+):((dbname|host)=(\w+))?;?((dbname|host)=(\w+))?/

      



But it can match mysql: host = localhost; host = localhost too ...

+1


a source







All Articles