1

Need some help on a problem please.

In fact I got a base64 string named "image" like that :

data:image/pjpeg;base64,iVBORw0KGgoAAAANSUhE...

I need to replace the part "data:image/pjpeg;base64," by "".

I try this way :

imageSrc = image.Replace("data:image/(png|jpg|gif|jpeg|pjpeg|x-png);base64,", "");

But it doesn't work.

Is somebody has an idea on that.

Thanks a lot

5 Answers 5

5

You should use the static Replace method on the Regex class.

imageSrc  = Regex.Replace(image, "data:image/(png|jpg|gif|jpeg|pjpeg|x-png);base64,", "");
Sign up to request clarification or add additional context in comments.

Comments

1

Well, for starters your code is doing String.Replace instead of Regex.Replace.

imageSrc = Regex.Replace(image, "data:image/(png|jpg|gif|jpeg|pjpeg|x-png);base64,", "");

But Regex is a rather heavy for this use case, why not just take everything after the comma?

imageSrc = image.SubString(image.IndexOf(",") + 1);

Comments

1

You are just using String.Replace, but you should use Regex.Replace for regular expressions.


But why not just use Substring?

imageSrc = image.Substring(image.IndexOf(',') + 1)

Since you know that your string is always starting with data:image/..., you don't need regular expressions at all.

Keep it simple and just take the substring after the first ,.

Comments

0

String.Replace() has no overload with regexp. Use Regex.Replace() instead.

Comments

-1

There is a mistake in your regex, you must specify ?: for images alternatives and use Regex object, so :

Regex.Replace("data:image/(?:png|jpg|gif|jpeg|pjpeg|x-png);base64,", "");

it should work

1 Comment

I'm not the downvoter, but the ?: is not required. That operator only tells the Regex engine not to create a backreference. Your solution works, and is more efficient, but it is not correct to say the original Regex has a mistake. I still maintain that Substring is the best solution here. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.