2

I'm fairly new and I couldn't get this to work properly.

I have this string

["string1","string2","string3","string4","string5","string6","string7","string8","string9","string10"]

And I want to get all values between the "

I think regex would be best to do the task.

Thanks for your help.

sloth
  • 95,484
  • 19
  • 164
  • 210
maddo7
  • 3,783
  • 6
  • 29
  • 48
  • Is this line coming from a file? – James Lawruk Aug 10 '12 at 13:29
  • possible duplicates http://stackoverflow.com/questions/2402797/regex-find-characters-between http://stackoverflow.com/questions/3697644/regex-match-text-in-between-delimiters – hometoast Aug 10 '12 at 13:29
  • 3
    Is it a bird? Is it a plane? Whatever it is, it's not a string. – 2v0mjdrl Aug 10 '12 at 13:30
  • Who knows? It could an array of strings. @Simon Whitehead has taken a punt in his answer on it being a single string that is missing the enlosing quotes, and missing \" for the embedded quotes. – Polyfun Aug 10 '12 at 13:34
  • Maybe you can use JavaScriptSerializer http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.deserializeobject – Matthew Aug 10 '12 at 13:44

4 Answers4

5

This will capture between the quotes:

(?<=")[\w]+(?!=")

An expanded example:

string s = "[\"string1\",\"string2\",\"string3\",\"string4\",\"string5\",\"string6\",\"string7\",\"string8\",\"string9\",\"string10\"]";

foreach (Match m in Regex.Matches(s, "(?<=\")[\\w]+(?!=\")")) {
    Console.WriteLine(m.Value);
}
Simon Whitehead
  • 60,641
  • 8
  • 104
  • 133
3

Since this looks like JSON, try using the JavaScriptSerializer class

string myString = "[\"string1\",\"string2\",\"string3\",\"string4\",\"string5\",\"string6\",\"string7\",\"string8\",\"string9\",\"string10\"]";

string[] strings = (new JavaScriptSerializer()).Deserialize<string[]>(myString);

foreach (string str in strings)
{
    Console.WriteLine(str);
}

Kinda seems overkill though.

Matthew
  • 23,095
  • 7
  • 70
  • 102
1

In my opinion, this is a job for Split rather than just Regex:

string str = "[\"string1\",\"string2\",\"string3\",\"string4\",\"string5\",\"string6\",\"string7\",\"string8\",\"string9\",\"string10\"]";
Regex rgx = new Regex("[\\[\\]\"]"); // get rid of the quotes and braces
str = rgx.Replace(str,""); 
string [] split = str.Split(','); // split on commas. that's it.

foreach (string s in split)
{
    Console.WriteLine(s);
}

This requires no special matching regex that you may to change if your quoted strings get messy. Consequently, it is (again, in my opinion) more elegant.

kevlar1818
  • 2,929
  • 5
  • 26
  • 42
0

If you mean you have a CSV string e.g.

"\"string1\", \"string2\", \"string3\"" 

Then you don't need a regex for something as trivial as this, you could use String.Split with a sprinkle of LINQ:

var values = csvString.Split(',').Select(s => s.Replace("\"", "").Trim());
James
  • 77,877
  • 18
  • 158
  • 228