Regex problem - any help greatfully accepted!

M

Martin Hart

I have a connection string that I would like to extract a part from, but
my knowledge does not extend far enough to resolve my problem.

I can have strings like:
"Integrated Security=SSPI;Persist Security Info=False;Initial
Catalog=GestionNet00001;Data Source=localhost;MultipleActiveResultSets=true"

or

"Integrated Security=SSPI;Persist Security Info=False;Initial
Catalog=GestionNet00001;Data Source=localhost"

I want to extract the "localhost" part of the string when (and only
when) it is preceded with "Data Source=". I have devised a regular
expression like this: "(?<=Data\s+Source\s*=)(.*)(?=[;\n\r$])".

This works fine for the first string as the "localhost" is suffixed with
a colon, but in the case of the second string it does not have a suffix,
and fails.

My Regex constructor look like this:
Regex regex = new Regex(@"(?<=Data\s+Source\s*=)(.*)(?=[;\n\r$])",
RegexOptions.IgnoreCase |
RegexOptions.CultureInvariant |
RegexOptions.IgnorePatternWhitespace |
RegexOptions.Compiled
);

Can anyone help me with this problem?

TIA,
MartinH.
 
K

Kevin Spencer

(?i)data\s*source\s*=\s*([^;]*)

I tend to like to put my options into the regular expression itself. This
one is case-insensitive. It also makes no assumptions about the location of
spaces. It's fairly simple, as are the rules for Connection Strings. It
simply looks for everything after the '=' character (and optional spaces)
that is not a semicolon. It puts that into Group 1.

--
HTH,

Kevin Spencer
Microsoft MVP
Professional Numbskull

Show me your certification without works,
and I'll show my certification
*by* my works.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top