Search code examples
c#stringumbraco

Create a regex to grab image value from node in umbraco


I'm trying to get the image from a node in umbraco using

var image = node.GetProperty("postImage").Value;

however I am getting

"{\r\n  \"focalPoint\": {\r\n    \"left\": 0.5,\r\n    \"top\": 0.5\r\n  },\r\n  \"src\": \"/media/8354/Image123Test.jpg\",\r\n  \"crops\": [\r\n    {\r\n      \"alias\": \"blogPost\",\r\n      \"width\": 200,\r\n      \"height\": 200\r\n    },\r\n    {\r\n      \"alias\": \"thumbnail\",\r\n      \"width\": 50,\r\n      \"height\": 50\r\n    },\r\n    {\r\n      \"alias\": \"featuredImage\",\r\n      \"width\": 320,\r\n      \"height\": 238\r\n    }\r\n  ]\r\n}"

returned.

Is it possible to come up with regex that will just return "/media/8354/Image123Test.jpg\" ?

thanks,


Solution

  • You could try something like this. It searches for \"src\": \" and takes everything until the next \"

        string test = "{\r\n  \"focalPoint\": {\r\n    \"left\": 0.5,\r\n    \"top\": 0.5\r\n  },\r\n  \"src\": \"/media/8354/Image123Test.jpg\",\r\n  \"crops\": [\r\n    {\r\n      \"alias\": \"blogPost\",\r\n      \"width\": 200,\r\n      \"height\": 200\r\n    },\r\n    {\r\n      \"alias\": \"thumbnail\",\r\n      \"width\": 50,\r\n      \"height\": 50\r\n    },\r\n    {\r\n      \"alias\": \"featuredImage\",\r\n      \"width\": 320,\r\n      \"height\": 238\r\n    }\r\n  ]\r\n}";
        string regx = "(?<=\\\"src\\\": \\\").+(?=\")";
    
        System.Text.RegularExpressions.Match mat = System.Text.RegularExpressions.Regex.Match(test, regx);