AJB AJB - 4 months ago 16
JSON Question

How to Parse a specific string in C#

I have this structure:

{
"longUrl" :"http://www.sample.com",
"bok" :1,
"url" :"http://pleasegetme.com ",
"title" :""
}
//equivalent
"{
\n \"longUrl\" :\"http://www.sample.com/\",
\n \"bok\" :1,
\n \"url\" :\"http://pleasegetme.com \",
\n \"title\" :\"\"\n
}"


I have this function

public string Domain1Helper(string longText)
{
Regex rgxUrl = new Regex("\"url\":\"(.*?)\"");
Match mUrl = rgxUrl.Match(longText);

string url = Regex.Replace(mUrl.Groups[1].Value, @"\\", "");
return url;
}


What I want to get is
http://pleasegetme.com
.

What is the wrong in my
Domain1Helper
method?

Answer

AJB, You have an error in your RegEx. That being said you should use a JSON deserializer, like JSON.NET. In the function Domain1Helper it should be:

Regex rgxUrl = new Regex("\"url\"\\s+:\"(.*?)\"");

Notice the \s+ ?