Apalabrados
Apalabrados

Reputation: 1146

Matching a result in c#

I have the following string

background-image: url('https://s3-eu-west-1.amazonaws.com/files.domain.com/uploads/image/file/168726/carousel_IMG_6455.jpg')

and I just want to get the image URL.

My code is:

image = image.Replace(@"'", "\"");
Match match = Regex.Match(image, @"'([^']*)");

Match.Success returns nothing, so I can not get the image URL.

Is there something missing? This used to work but not now.

Upvotes: 1

Views: 251

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627607

No need for a regex, just

  • Split the string with ' substring
  • Find the element starting with http
  • Return the first found item.

C# demo:

var s = "background-image: url('https://s3-eu-west-1.amazonaws.com/files.domain.com/uploads/image/file/168726/carousel_IMG_6455.jpg')";
var res = s.Split(new[] {"'"}, StringSplitOptions.None)
    .Where(v => v.StartsWith("http"))
    .FirstOrDefault();
Console.WriteLine(res);
// => https://s3-eu-west-1.amazonaws.com/files.domain.com/uploads/image/file/168726/carousel_IMG_6455.jpg 

If you need to use a regex, use the standard regex to match a string between two strings, start(.*?)end where (.*?) captures into Group 1 any 0 or more chars other than a newline, as few as possible as the *? quantifier is lazy:

var s = "background-image: url('https://s3-eu-west-1.amazonaws.com/files.domain.com/uploads/image/file/168726/carousel_IMG_6455.jpg')";
var res = Regex.Match(s, @"'(.*?)'").Groups[1].Value ?? string.Empty;
Console.WriteLine(res);
// => https://s3-eu-west-1.amazonaws.com/files.domain.com/uploads/image/file/168726/carousel_IMG_6455.jpg

See another C# demo

Upvotes: 1

Ehz
Ehz

Reputation: 2067

The regex of: (\".*\")

Will match the URL given the input string: background-image: url("https://s3-eu-west-1.amazonaws.com/files.domain.com/uploads/image/file/168726/carousel_IMG_6455.jpg")

image = image.Replace(@"'", "\"");
Match match = Regex.Match(image, "(\\\".*\\\")");

Edit: If you are looking for something that will match pairs of single quotes or double quotes you could use:

(\".*\"|'.*')

Match match = Regex.Match(image, "(\\\".*\\\"|'.*')");

Upvotes: 0

Iqon
Iqon

Reputation: 1992

The following pattern achieves your result, without the usage of string.replace.

var pattern = @"&#39;(?<url>.*)&#39;";
Match match = Regex.Match(image, pattern);
Console.WriteLine($"Math: {match.Groups["url"].Value}");

If you want the " surrounding the string, add this:

var result = $"\"{match.Groups["url"].Value}\""

Upvotes: 1

Related Questions