0

I am trying to split a line into a key / value pair by using Regex. Can anyone give me a hint on how to split the line below properly?

The line looks like this:

"key"="some=value"

I'd like to split it into:

key  
some=value

I have to read an string resource file, which looks like this:

"key1"="translation number one";  
"key2"="translation number = the second number";   

When I do a

string[] elements = Regex.Slit(line, "=");  

I get 3 elements instead of the 2 I want. So basically I want to Split at the "=" outside the quotes

Cœur
  • 37,241
  • 25
  • 195
  • 267
frank
  • 1,217
  • 2
  • 10
  • 18
  • Can you please share your code? Where exactly are you getting stuck? – Ryan Gates Feb 27 '14 at 16:02
  • `mystring.Split('\"');` returns `string[]`, elements 1 and 3 contain values you want. No need for regex here. – Anri Feb 27 '14 at 16:04
  • alwayes you have the same line the key alwayes empty and = after " ? – Akrem Feb 27 '14 at 16:05
  • I have to read an string resource file, which looks like this: `code`"key1"="translation number 1"; "key2"="translation number = the second number"; When I do a Regex.Slit(line, "=") I get 3 elemtens instead of the two I want. So basically I want to Split at the "=" outside the quotes – frank Feb 27 '14 at 16:06
  • Split on `"="` then replace `^"` and `"$` with nothing? – tenub Feb 27 '14 at 16:08
  • 1
    possible duplicate of [Regular Expression to split on spaces unless in quotes](http://stackoverflow.com/questions/554013/regular-expression-to-split-on-spaces-unless-in-quotes) – Kendall Frey Feb 27 '14 at 16:12
  • First of all, why would you ever want to do this? This is basically a JSON string, so why not just use the built in deserialization methods of C#? You're basically trying to create a serializer. – user1477388 Feb 27 '14 at 16:49
  • @user1477388 since when json has `=` as a key-value delimiter? – Anri Feb 27 '14 at 17:02
  • @Anri It would be easier to just convert your equal signs (that are outside of the double quotes) to colons and be done with it. – user1477388 Feb 27 '14 at 17:04
  • You're trying to interpret it as a key/value pair with double quote delimeters, when in fact you don't give any hint of quoting rules. Quoting rules are delimiters that must have provision for escaping a delimiter constant, otherwise quoting is an invalid concept. –  Feb 27 '14 at 17:09

2 Answers2

1

First strip the string for quote(") for both ends. Then split the string using regex:

string []splits = Regex.Split(input.Trim('"'), "\\s*\"\\s*=\\s*\"\\s*");
Sabuj Hassan
  • 38,281
  • 14
  • 75
  • 85
0

Assumes single key=value per line

^"(?<key>[^"]+)"="(?<value>.*)"$
LB2
  • 4,802
  • 19
  • 35