Reputation: 93
Hoping this would be an easy one for regex experts out there.
I have a text file that looks like this:
blah blah blah
[Image "pasted.bmp-20160720140433"]
blah blah
[Image "pasted.bmp-20160720140458"]
blah blah
[Image "download"]
blah blah
blah blah [Image "download3"] [Image "download5"] blah blah
I wish to replace the [Image "pasted.bmp-20160720140433"] with base64 embedded images. The image placements always start with "[Image " and always end with "]" the enclosing bracket.
Is there an easy regex replace that can do the job?
edit:
Ultimately I would like the string to be html compliant like this:
blah blah blah
<img src='data:image/png;base64,data_which_I_get_from_using_the_file_name' />
blah blah blah
Thank you very much.
Upvotes: 0
Views: 1143
Reputation: 877
\[Image "([.\-\w]+)"\]
will match your pattern
A little explanation:
\[Image "
matches the first part of your pattern. The [
is escaped here as []
's have special meaning in the Regex language
[.\-\w]
is a list of characters - .
matches a period, and \-
a hyphen. \w
matches any word character, which is A-Z, a-z, or 0-9
The +
means to match as many times in a row as possible
The ()
's around [.\-\w]+
make it a capturing group, which means when a match is found, the image name will be made available.
Finally, "\]
matches the end of your pattern.
Note that when using this in C# you will need to escape certain characters to get the right string such as "\\[Image \"([.\\-\\w]+)\"]"
or using an @-quoted string like @"\[Image ""([.\-\w]+)""\]"
Also, in the future, there are websites that can help with generating Regular Expressions and breaking down how they work, try inputting the above into regex101
Now, using Regex.Replace
directly won't work, as I assume the base64 content will depend on the image name. In this case, you can use the Match
class
An incomplete example might look like this:
string pattern = @"\[Image ""([.\-\w]+)""\]";
Regex rgx = new Regex(pattern);
string file = "...";
foreach (Match match in rgx.Matches(file))
{
// Modify file here
// match.Index will have the position of a match
// match.Value will have the capture, e.g. "download3"
}
Upvotes: 3