0

I have 2 different types of connection strings (because of legacy reasons that I can't fix everywhere for various reasons which are irrelevant here). I need to break them up into key/value pairs. Here are the sample connection strings:

1. Server=SomeServer;Database=SomeDatabase;Something=Hello
2. Server=SomeServer,Database=SomeDatabase;Something=Hello
3. Server=SomeServer,1111;Database=SomeDatabase;Something=Hello 

For the first 2 cases, I can use the regex:

(?<Key>[0-9A-z\s]+)=(?<Val>[0-9A-z\s,]+?[0-9A-z\s]+)

For the third one, I can use the regex:

(?<Key>[0-9A-z\s]+)=(?<Val>[0-9A-z\s]+?[0-9A-z\s,]+)

How do I turn this into one regex that would work for all cases?

Denis
  • 11,796
  • 16
  • 88
  • 150
  • What's the purpose of `[0-9A-z\s,]+?[0-9A-z\s]+`? It's [dangerous](http://www.regular-expressions.info/catastrophic.html). – Aran-Fey Jan 08 '15 at 15:01
  • 1
    Maybe [use DbConnectionStringBuilder](http://stackoverflow.com/questions/8524611/parsing-a-connection-string) would work? – Alexei Levenkov Jan 08 '15 at 15:13
  • @Rawing: The first part did a lazy match which caught the first letter after the "=" - then I tried to capture the rest with a greedy match. – Denis Jan 08 '15 at 15:19

2 Answers2

4

You can just use the below regex

(?<Key>[^=;]+)=(?<Val>[^;]+)

What the above uses is negated character class. [^;]+ will select everything till the first ; it encounters.

DEMO (I've removed the named groups for testing. It would work well in C#, however)

Amit Joki
  • 58,320
  • 7
  • 77
  • 95
1

Here is my suggestion.

(?<key>[^=;,]+)=(?<val>[^;,]+(,\d+)?)

The semicolon is a delimiter as is the comma if it is not immediately followed by numbers.

Francis Gagnon
  • 3,545
  • 1
  • 16
  • 25