-2

I have special case where I need to replace string

(src="cid:image001.png@01D081C1.C5908B40")

with the following

(src="\\resources\\images\\image001.png")

with in the given text.

It should replace in all occurrences where ever it appears in given text.

I tried like this but its not working as expected.

fileName ="image001.png"; 

Regex.Replace(body, "[src=\"cid:" + fileName + "@](*)[\"]", "src=\"\\Resources\\Email\\" + emailID + "\\" + fileName + "\"");
Biffen
  • 6,249
  • 6
  • 28
  • 36
  • @Biffen I need it in C#. – Mahesh Kakkireni May 08 '15 at 15:24
  • 1
    Side note: please consider using MSDN to get initial samples of how to use functions. I.e. [Regex.Replace](https://msdn.microsoft.com/en-us/library/xwewhkd1%28v=vs.110%29.aspx) shows code that works and it could help understanding why your version did not. – Alexei Levenkov May 08 '15 at 15:31

3 Answers3

0

There is a couple of things to remember:

  • When using variables to initialize regex patterns, use Regex.Escape (e.g. you have a dot in image001.png, so it must be escaped as image001\.png in the pattern)
  • When using variables in replacement strings, it is a good idea to add .Replace("$","$$") to replace literal $s (e.g. emailID.Replace("$", "$$")).
  • It is a good idea to use verbatim string literals when writing regex patterns, so as not to use double-escaping (that facilitates rgex writing and testing in online and other regex testing tools).

I cannot guess what your emailID variable looks like, thus, I would not use a variable in the replacement string to obtain the output you want.

So, the code I suggest:

var fileName = "image001.png";
var body = "(src=\"cid:image001.png@01D081C1.C5908B40\")";
var pattern = @"(\(src="")cid:(" + Regex.Escape(fileName) + @")@.*""\)"; // will look like (\(src=")cid:(image001\.png)@.*"\)
var restt = Regex.Replace(body, pattern, @"$1\\resources\\images\\$2"")");

Output:

enter image description here

enter image description here

Community
  • 1
  • 1
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
-1
fileName =
  Regex.Replace(body,
                "[src=\"cid:" + fileName + "@](*)[\"]",
                "src=\"\\Resources\\Email\\" + emailID + "\\" + fileName + "\"");
dg99
  • 5,456
  • 3
  • 37
  • 49
Aron
  • 15,464
  • 3
  • 31
  • 64
-1

This works

    string input = "(src=\"cid:image001.png@01D081C1.C5908B40\")";
    string replacement = "src=\"\\\\resources\\\\images\\\\$1\"";
    Regex rgx = new Regex("src=\"cid:(image[0-9]+\\.png)@[A-Za-z0-9]+\\.[A-Za-z0-9]+\"");
    Console.WriteLine(rgx.Replace(input, replacement));

Output: (src="\\resources\\images\\image001.png")

DEMO

54l3d
  • 3,913
  • 4
  • 32
  • 58