tags:

views:

61

answers:

2

I'm trying to get to grips with regular expressions:

I have a database connection string and I'd like to use a regular expression to identify specific Keys and Values within it.

For example

server=foo;database=bar;uid=foo;pwd=bar

I'd like something to return "database=bar;" using the 'database' key to identify it, ideally it would be case insensitive. I can do this using normal code, but I think that this is exactly the sort of thing for which regular expressions were designed.

+3  A: 
database=([^;]*);

should do the trick. It matches the string database=, followed by any sequence of zero or more non-semicolons, followed by a semicolon. The sequence of non-semicolons is parenthesized, so you can later extract the text that matched this part of the regex.

How to specify case insensitivity, and how to extract the value of the parenthesized thing, depends on the language you're using.

Thomas
This is exactly what I was after and much more elegant that the code I'd originally written. Thank you Thomas.
David_Jarrett
A: 

Not sure why you would use a REGEX since you can write a string parser that would first parse all items into an array at the ; token, then parse each item of the array by = and you have the first part and second part so the keyword and its value.

Here is an example in C#

string Configurationstring = "server=foo;database=bar;uid=foo;pwd=bar";
string[] ConfigurationPart = Configurationstring.Split(';');
foreach (string ConfigurationSubPart in ConfigurationPart)
{
    string[] SubPart = ConfigurationSubPart.Split('=');
    if (SubPart[0].Trim() = "database")
    {
        System.Console.WriteLine(SubPart[1].Trim());
    }
}
Ioxp